2016-07-20 6 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

functoinコールバックのこれに結合しています。これでクリアされます –

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.

は、だから、この関数以下は、ちょうど私が遊んでた基本を理解するために

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