angular2 http解析承诺

时间:2017-01-31 17:26:51

标签: angular promise angular-routing

晚上好兄弟

我正试图进入angular2并遇到一个让我无法继续前进的问题。

服务:

  getProject(id: number): any {
    var url = this.ProjectsUrl + '/'+ id;
     return this.http.get(url)
      .toPromise()
      .then(response => {
        console.log(response.json().data as Project);
      })
      .catch(this.handleError);
  }

组件:

  getProject(id:number){
       this.projectService
        .getProject(id)
        .then(project => this.project = project); 
  }

ngOnInit()

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      this.getCustomers();
      console.log('b4 getProj')
      this.getProject(+params["id"]);
      console.log('after getProj')
     });
  }

输出:

b4 getProj
after getProj
Object { Project }

我无法弄清楚为什么承诺不会得到解决?有小费吗?

2 个答案:

答案 0 :(得分:1)

Angular2的一个好处是它支持Observables代替Promises。

如果您想使用Observable代替Promises,可以使用以下代码:

服务:

 getProject(id: number): any {
    var url = this.ProjectsUrl + '/'+ id;
     return this.http.get(url)
      .map(response => {
        response.json().data as Project;
      })
      .catch(this.handleError);
  }

组件:

  getProject(id:number){
           this.projectService
            .getProject(id)
            .subscribe(project => {
             this.project = project
           }); 
        }

我希望这会有所帮助。

请记住在您的服务中添加以下声明:

import { Observable } from 'rxjs';

答案 1 :(得分:0)

我想这就是你想要的:

  getProject(id:number){
    return this.projectService // <<<=== added return
        .getProject(id)
        .then(project => this.project = project); 
  }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      this.getCustomers();
      console.log('b4 getProj')
      this.getProject(+params["id"])
      .then(_ => console.log('after getProj')); // <<<=== changed
     });
  }