2

My getHeroes function is supposed to return Hero[] Objects, but I cannot access its methods. Am I doing something wrong ?

hero.ts

export class Hero {
  id: number;
  name: string;

  getName(): string {
    return this.name;
  }
}

heroes.service.ts

getHeroes (): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl)
      .pipe(
        catchError(this.handleError('getHeroes', []))
      );
  }

heroes.component.ts

getHeroes(): void {
  this.heroesService.getHeroes()
    .subscribe(heroes => {
      this.heroes = heroes;
      this.heroes.forEach((hero) => console.log(hero));
      this.heroes.forEach((hero) => console.log(hero.getName())); //ERROR here
    });
}

I'm getting a ERROR TypeError: hero.getName is not a function on the last line.

Here is a live version Live link

4
  • Hero should be a interface instead of class.. Commented Oct 29, 2018 at 9:10
  • Check the following link. stackoverflow.com/questions/47748170/… Commented Oct 29, 2018 at 9:12
  • @JeevaJsb why ? I still have an error event when hero is an interface. Commented Oct 29, 2018 at 9:14
  • Interface cannot be instantiate. For good practice use interface instead of class. For instantiate, please refer @ritaj's answer Commented Oct 29, 2018 at 9:24

1 Answer 1

7

Http call returns an object (actually just a JSON string which will later by parsed by HttpClient) with id and name and no function. You can check that in your network tab.

What you could do is just use a contructor:

export class Hero {
  id: number;
  name: string;

  getName(): string {
    return this.name;
  }

  contructor(id, name) {
    this.id = id;
    this.name = name;
   }
}

And later map the response from http call to the object you need:

getHeroes (): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl)
      .pipe(
        map(hero => new Hero(hero.id, hero.name),
        catchError(this.handleError('getHeroes', []))
      );
  }
Sign up to request clarification or add additional context in comments.

1 Comment

This would be the answer. Since we need to instantiate the class if the properties should be accessible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.