我有代码
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标记为位置。
答案 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
};
});
}