In my Plunker here(改性Tour of Heroes从官方文档的应用程序),我创造了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);
}
作为调用heroesExist()
米模板中的方法
<button (click)="heroesExist()">Do Heroes Exist?</button>
我对它的行为感到困惑。
当我点击做英雄存在吗?按钮,我希望控制台(和警报弹出)登录“doHeroesExist叫..真正的”,而是它记录了服务功能的整个身体:)
doHeroesExist叫..ƒ({ console.log(“doHeroesExist called ..”,this.heroesExist); (“doHeroesExist called ..”+ JSON.stringify(this.heroesExist)); return this.heroesExist; }
这是怎么发生的?
为什么服务不正确评估heroesExist = true;
,因为它在服务的构造函数中定义?
PLUNKER LINK:https://plnkr.co/edit/MBEGkqnV5kie9PB3az9K?p=preview
你正在对待'this.heroService.doHeroesExist'就像一个属性,rath呃比调用它像一个函数'this.heroService.doHeroesExist()'。最后遗漏了一些人。这是你真正需要的吗? –