2016-07-20 46 views
0

我正在嘗試用於Typescript的Anuglar Heroes Tutorial。當試驗服務以下代碼工作:用匿名函數替換箭頭函數導致異常

getHeroes() { 
    this.heroService.getHeroes().then(heroes => this.heroes = heroes); 
} 

但是,當我改變的代碼如下它不工作

getHeroes(){ 
    this.heroService.getHeroes().then(function (heroes:Hero[]) { 
     this.heroes = heroes; 
    }) 
} 

我收到以下錯誤:

Unhandled Promise rejection: this is null ; Zone: angular ; Task: Promise.then ; Value: TypeError: this is null
this.heroes = heroes;

我已經在課堂裏定義了英雄

heroes: Hero[]; 

回答

1

這是因爲當您使用正常功能而不是arrow function時,您失去了this的範圍。如果你不喜歡使用的脂肪箭頭功能

getHeroes(){ 
    this.heroService.getHeroes().then(function (heroes:Hero[]) { 
     this.heroes = heroes; 
    }.bind(this)); 
} 

可以使用Function.prototype.bind功能。

+0

只是爲了瞭解我玩弄的基礎。這清除它 –

0

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous. These function expression are best suited for non-method functions.

因此,這在下面功能綁定到這個回調的functoin

getHeroes(){ 
    this.heroService.getHeroes().then(function (heroes:Hero[]) { 
     this.heroes = heroes; 
    }) 
}