Angular 2 Promise问题

时间:2016-02-28 00:44:33

标签: typescript angular es6-promise

我开始学习Angular 2,我遇到使用Promise.then从服务返回我的对象​​的问题。我目前只使用固定数组(COACHES)伪造数据库调用。我服务中的功能如下

getCoach(id: number) {
    return Promise.resolve(COACHES).then(
        coaches => coaches.filter(coach => coach.id == id)[0]
    );
}

然后我在ngOnInit钩子的coach_detail.component.ts中使用它,以使用Route Params获取我想要的coach对象:

export class CoachDetailComponent implements OnInit {

    coach: Coach;

    constructor(
        private _coachService: CoachService,
        private _routeParams: RouteParams) {}

    ngOnInit() {
        let id = +this._routeParams.get('id');
        this._coachService.getCoach(id).then(coach => this.coach = coach);
        console.log(this.coach);
    }
}

我可以在我的控制台中看到承诺会返回到我的组件,但console.log(this.coach)将返回undefined

我非常感谢任何帮助,因为我在不同的组件中使用类似的逻辑来返回整个教练列表,这很好用!

1 个答案:

答案 0 :(得分:5)

在承诺链被提取之前,您的console.log()被调用。

ngOnInit() {
    let id = +this._routeParams.get('id');
    this._coachService.getCoach(id).then(coach => { 
      this.coach = coach 
      console.log(this.coach); // not undefined
    });
    console.log(this.coach); // undefined
}