Reputation: 81
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.
Upvotes: 0
Views: 246
Reputation: 164129
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
};
});
}
Upvotes: 2