Angular:向组件字段提供对服务功能的引用,并从模板中调用它无法按预期方式工作 [英] Angular: Giving a component field a reference to a service function and calling it from template not working as expected
问题描述
在这里我的柱塞中(已修改
In my Plunker here (modified Tour of Heroes app from official docs) I created this method in the 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被调用.服务功能的整个主体:
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称为..ƒ(){ console.log("doHeroesExist被称为..",this.heroesExist); alert("doHeroesExist被调用.." + JSON.stringify(this.heroesExist)); 返回this.heroesExist; }
doHeroesExist called.. ƒ () { console.log("doHeroesExist called..", this.heroesExist); alert("doHeroesExist called.." + JSON.stringify(this.heroesExist)); return this.heroesExist; }
为什么会这样?
为什么服务未正确评估在服务的构造函数中定义的heroesExist = true;
?
Why doesn't the service correctly evaluate heroesExist = true;
as it is defined in the service's constructor?
PLUNKER链接: https://plnkr.co/edit/MBEGkqnV5kie9PB3az9K?p=preview
PLUNKER LINK: https://plnkr.co/edit/MBEGkqnV5kie9PB3az9K?p=preview
推荐答案
当您传递该函数并在另一个上下文中稍后调用它时,该函数中this
的上下文将丢失.这就是为什么您看到警报显示"doHeroesExist被调用..未定义"的警告的原因,因为服务方法中的this
并不指向服务本身.
When you pass the function around and call it later in another context, the context of this
in the function is lost. That's why you see the alert showing "doHeroesExist called.. undefined", as this
in your service method isn't referring to the service itself.
要解决此问题,请在将函数作为变量返回之前,将上下文绑定到它:
To solve it, before returning the function as a variable, bind the context to it:
this.heroesExist = this.heroService.doHeroesExist.bind(this.heroService);
这篇关于Angular:向组件字段提供对服务功能的引用,并从模板中调用它无法按预期方式工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!