CodyBugstein
CodyBugstein

Reputation: 23322

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

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

Upvotes: 3

Views: 1993

Answers (2)

Atul Chaudhary
Atul Chaudhary

Reputation: 3736

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

Upvotes: 1

Harry Ninh
Harry Ninh

Reputation: 16758

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

Upvotes: 4

Related Questions