2016-02-28 110 views
3

我開始學習Angular 2,並且遇到了使用Promise.then從服務返回對象的問題。我目前只使用固定數組(COACHES)僞造數據庫調用。在我服務的功能如下Angular 2 Promise問題

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

然後我用這在我的coach_detail.component.ts在ngOnInit鉤來獲得主教練的對象我想用路線PARAMS:

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

任何幫助是非常讚賞,因爲我使用了相似的邏輯在不同的組件返回教練的完整列表,並能正常工作!

回答

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 
} 
+0

但是我不是在組件中定義的「coach」變量上調用console.log嗎? 'this._coachService.getCoach(id)'應該將返回的對象分配給'this.coach'。我的問題的確是我的箭頭功能沒有正確分配 –

+0

嗯,你的代碼看起來很好。你能用例子來創造一個沉睡者嗎? – Sasxa

+0

有點笨拙,但在這裏你去:https://plnkr.co/edit/Sk4GH2mgoJ2XkQ7Tr1qN我談論的問題是當你進入「教練」頁面,然後嘗試選擇一個教練的名字。 –