#angularjs #angular #typescript
#angularjs #угловой #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:
Вам нужно привязать переданную функцию к 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));
}
Или используйте функцию со стрелкой, которая сохраняет область действия этого:
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
};
});
}