2017-02-10 17 views
1

Angular 2僅使用arrw函數呈現,或者我做錯了什麼?Angular 2僅使用箭頭函數呈現

this.service.getData(o).subscribe(res => { 
    this.data = res.data 
    this.view = res.view 
}); 

實際呈現我的組件,但是

this.service.getData(o).subscribe(function(res){ 
    this.data = res.data 
    this.view = res.view 
}); 

不是錯誤,但我的組件未更新

回答

1

,因爲你失去context

let self = this; 

this.service.getData(o).subscribe(function(res){ 
    self.data = res.data 
    self.view = res.view 
}); 

的認購採取一個observer對象。所以在你的代碼中this的意思是:observer對象的上下文。

或使用這種方法:

this.service.getData(o).subscribe((function(res){ 
    this.data = res.data 
    this.view = res.view 
}).bind(this));