In my Plunker here(从官方文档中修改了Tour of Heroes app)我在 hero.service
中创建了这个方法
doHeroesExist(): boolean {
console.log("doHeroesExist called..", this.heroesExist);
alert("doHeroesExist called.." + JSON.stringify(this.heroesExist));
return this.heroesExist;
}
并在 app.component
类中使用它
ngOnInit(): void {
//this.getHeroes();
this.heroesExist = this.heroService.doHeroesExist;
console.log("app ngOnInit called...", this.heroesExist);
}
as在模板中调用 heroesExist()
方法
<button (click)="heroesExist()">Do Heroes Exist?</button>
I am puzzled by its behaviour.
当我点击Do Heroes Exist?按钮,我希望控制台(和警报弹出窗口)记录 "doHeroesExist called.. true" ,但它会记录服务功能的整个主体:
doHeroesExist调用..ƒ(){console.log(“doHeroesExist called ..”,this.heroesExist); alert(“doHeroesExist called ..”JSON.stringify(this.heroesExist));返回this.heroesExist; }
为什么会这样?
为什么服务没有正确评估 heroesExist = true;
,因为它是在服务的构造函数中定义的?
PLUNKER链接:https://plnkr.co/edit/MBEGkqnV5kie9PB3az9K?p=preview
2 回答
当您传递函数并稍后在另一个上下文中调用它时,函数中的
this
的上下文将丢失 . 这就是为什么你看到警告显示"doHeroesExist called.. undefined",因为你的服务方法中的this
并不是指服务本身 .要解决它,在将函数作为变量返回之前,将上下文绑定到它:
在你的plunker只需更换
<button (click)="heroesExist()">Do Heroes Exist?</button>
同
这对我有用