在angular2 typeScript

时间:2016-10-13 09:15:15

标签: angularjs angular typescript

我有代码

  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
  });
}

如何将getHeroes标记为位置。

1 个答案:

答案 0 :(得分:2)

您需要将bind传递的函数发送到this,以便保存范围:

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
        };
    });
}