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 来自官方文档的应用)我在 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>
我对它的行为感到困惑。
当我点击 Do Heroes Exist? 按钮时,我希望控制台(和警报弹出窗口)记录 "doHeroesExist called.. true",而是记录服务函数的整个主体:
doHeroesExist called.. ƒ () {
console.log("doHeroesExist called..", this.heroesExist);
alert("doHeroesExist called.." + JSON.stringify(this.heroesExist));
return this.heroesExist;
}
为什么会这样?
为什么服务不能正确评估 heroesExist = true;
,因为它在服务的构造函数中定义?
当您传递函数并稍后在另一个上下文中调用它时,函数中 this
的上下文将丢失。这就是为什么您会看到显示 "doHeroesExist called.. undefined" 的警报,因为您的服务方法中的 this
并不是指服务本身。
要解决它,在将函数作为变量返回之前,将上下文绑定到它:
this.heroesExist = this.heroService.doHeroesExist.bind(this.heroService);
在你的 plunker 中只需替换 <button (click)="heroesExist()">Do Heroes Exist?</button>
和
<button (click)="heroService.doHeroesExist()">Do Heroes Exist?</button>
对我有用
In my Plunker here (modified 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
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>
我对它的行为感到困惑。
当我点击 Do Heroes Exist? 按钮时,我希望控制台(和警报弹出窗口)记录 "doHeroesExist called.. true",而是记录服务函数的整个主体:
doHeroesExist called.. ƒ () { console.log("doHeroesExist called..", this.heroesExist); alert("doHeroesExist called.." + JSON.stringify(this.heroesExist)); return this.heroesExist; }
为什么会这样?
为什么服务不能正确评估 heroesExist = true;
,因为它在服务的构造函数中定义?
当您传递函数并稍后在另一个上下文中调用它时,函数中 this
的上下文将丢失。这就是为什么您会看到显示 "doHeroesExist called.. undefined" 的警报,因为您的服务方法中的 this
并不是指服务本身。
要解决它,在将函数作为变量返回之前,将上下文绑定到它:
this.heroesExist = this.heroService.doHeroesExist.bind(this.heroService);
在你的 plunker 中只需替换 <button (click)="heroesExist()">Do Heroes Exist?</button>
和
<button (click)="heroService.doHeroesExist()">Do Heroes Exist?</button>
对我有用