0

I have code

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

How can I call getHeroes marked position.

1 Answer 1

2

You need to bind the passed function to this so that the scope is saved:

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

Or use an arrow function which saves the scope of this:

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

But getHeroes is async, so if you want to wait for it you'll need to do:

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
        };
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.