[英]Angular 2 Promise issue
I am starting to learn Angular 2 and I am having issues with using Promise.then to return my object from a service. 我开始学习Angular 2,我遇到使用Promise.then从服务返回我的对象的问题。 I am currently only using a fixed array (COACHES) for faking a database call. 我目前只使用固定数组(COACHES)伪造数据库调用。 The function in my service is as follows 我服务中的功能如下
getCoach(id: number) {
return Promise.resolve(COACHES).then(
coaches => coaches.filter(coach => coach.id == id)[0]
);
}
I then use this in my coach_detail.component.ts in an ngOnInit hook to get the coach object I want using Route Params: 然后我在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);
}
}
I can see in my console that the promise is returning back to my component but console.log(this.coach)
is returning as undefined
我可以在我的控制台中看到promise将返回到我的组件,但console.log(this.coach)
将返回undefined
Any help is much appreciated as I use a similar logic in a different component to return the entire list of coaches and this works fine! 任何帮助都非常感谢,因为我在不同的组件中使用类似的逻辑来返回整个教练列表,这很好用!
Your console.log()
is called before promise chain is exacuted. 在对promise chain进行exacuted之前调用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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.