在我的 Plunker 里(修改的英雄之旅来自官方文档的应用程序)我在hero.service
doHeroesExist(): boolean {
console.log("doHeroesExist called..", this.heroesExist);
alert("doHeroesExist called.." + JSON.stringify(this.heroesExist));
return this.heroesExist;
}
并在中使用它app.component
class
ngOnInit(): void {
//this.getHeroes();
this.heroesExist = this.heroService.doHeroesExist;
console.log("app ngOnInit called...", this.heroesExist);
}
称为heroesExist()
模板中的方法
<button (click)="heroesExist()">Do Heroes Exist?</button>
我对它的行为感到困惑。
When I click the Do Heroes Exist? button, I expect the console (and alert popup) to log "doHeroesExist called.. true", but instead it logs the entire body of the service function:
doHeroesExist 称为.. f () {
console.log("doHeroesExist 称为..", this.heroesExist);
Alert("doHeroesExist 称为.." + JSON.stringify(this.heroesExist));
返回 this.heroesExist;
}
为什么会发生这种情况?
为什么服务无法正确评估heroesExist = true;
正如它在服务的构造函数中定义的那样?
笨蛋链接:https://plnkr.co/edit/MBEGkqnV5kie9PB3az9K?p=preview