2016-10-13 9 views
0

私はgetHeroesの位置をマーク呼び出すことができますどのようにコードコール機能

constructor(private heroService :HeroService) {} 

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

    addHero(hero :Hero) { 
     this.heroService.create(hero).then(function(response){ 
     //call getHeroes here 
    }); 
} 

を持っています。

答えて

2

あなたはスコープが保存されるようにthisに渡された関数をbindする必要があります。

constructor(private heroService :HeroService) {} 

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

addHero(hero :Hero) { 
    this.heroService.create(hero).then(function(response) { 
     this.getHeroes(); 
    }.bind(this)); 
} 

またはこの範囲を保存しarrow functionを使用します。

addHero(hero :Hero) { 
    this.heroService.create(hero).then(response => { 
     this.getHeroes(); 
    }); 
} 

しかしgetHeroesは非同期です、あなたがそれを待つことを望むなら、あなたはする必要があります:

constructor(private heroService :HeroService) {} 

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

addHero(hero :Hero) { 
    this.heroService.create(hero).then(response => { 
     this.getHeroes().then(() => { 
      // do what ever 
     }; 
    }); 
}