Angular:为组件字段提供对服务功能的引用并从模板中调用它没有按预期工作 [英] Angular: Giving a component field a reference to a service function and calling it from template not working as expected

查看:19
本文介绍了Angular:为组件字段提供对服务功能的引用并从模板中调用它没有按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里我的Plunker(修改了Tour of Heroes 应用程序来自官方文档)我在 hero.service

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>

我对它的行为感到困惑.

当我点击 Do Heroes Exist? 按钮时,我希望控制台(和警报弹出窗口)记录 doHeroesExist called.. true",但它记录了服务功能的整个主体:

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 called.. undefined",因为您的服务方法中的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆