2016-07-20 43 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; 
    }) 
}