Angular: Giving a component field a reference to a service function and calling it from template not working as expected

丶灬走出姿态 提交于 2020-01-11 07:29:28

问题


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;
  }

and use it in the app.component class

  ngOnInit(): void {
    //this.getHeroes();
    this.heroesExist = this.heroService.doHeroesExist;
    console.log("app ngOnInit called...", this.heroesExist);

}

as call the heroesExist() method in the template

<button (click)="heroesExist()">Do Heroes Exist?</button>

I am puzzled by its behaviour.

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 called.. ƒ () { console.log("doHeroesExist called..", this.heroesExist); alert("doHeroesExist called.." + JSON.stringify(this.heroesExist)); return this.heroesExist; }

Why is this happening?

Why doesn't the service correctly evaluate heroesExist = true; as it is defined in the service's constructor?

PLUNKER LINK: https://plnkr.co/edit/MBEGkqnV5kie9PB3az9K?p=preview


回答1:


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);



回答2:


In ur plunker just replace <button (click)="heroesExist()">Do Heroes Exist?</button>

with

 <button (click)="heroService.doHeroesExist()">Do Heroes Exist?</button>

That worked for me



来源:https://stackoverflow.com/questions/46657227/angular-giving-a-component-field-a-reference-to-a-service-function-and-calling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!