CodyBugstein
CodyBugstein

Reputation: 23322

Angular service is referenced but not called, yet still "returns" correct value

In this Plunk, I've made a minor modification to the Angular.io tutorial.

I've added a function to the heroes.service called doHeroesExist. However, I never call it. The only thing I do it assign it to a variable in the app.component

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

And here is the doHeroesExist function inside the hero.service.ts file.

  doHeroesExist(): boolean {
    console.log("doHeroesExist called..", this.doHeroesExist);
    return this.doHeroesExist;
  }

I am puzzled.

Why does it say true in the console log? Shouldn't it output the body of the function as string? Also the console.log inside the doHeroesExist is never printed - further proof it's not called!

Upvotes: 1

Views: 17

Answers (1)

Pac0
Pac0

Reputation: 23174

EDIT :

You forgot to mention that you had that defined in your service:

  doHeroesExist: boolean; 

  constructor() {
    this.doHeroesExist = true;
  }

not a good idea to have a member method and a member field with the same name...

Whatever is the definition of doHeroesExist was (function, other variable...) , in your constructor you just assign it the value of true. So it becomes a boolean with the value true.

That's it. I am surprised it compiles due to the name clash, but in any case the behaviour is clearly caused by your constructor.

Upvotes: 1

Related Questions