Angular:HttpClient服务和Observable自定义类型

Hss*_*sen 0 httpclient typescript angular

我的getHeroes函数应该返回Hero[]Objects,但是我无法访问它的方法.难道我做错了什么 ?

hero.ts

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

  getName(): string {
    return this.name;
  }
}
Run Code Online (Sandbox Code Playgroud)

heroes.service.ts

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

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
    });
}
Run Code Online (Sandbox Code Playgroud)

ERROR TypeError: hero.getName is not a function在最后一行得到了一个.

这是一个实时版本Live链接

rit*_*taj 5

Http调用返回一个对象(实际上只是一个JSON字符串,稍后将由HttpClient解析)具有id和name而没有函数.您可以在网络选项卡中查看.

你能做的就是使用一个构造函数:

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

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

  contructor(id, name) {
    this.id = id;
    this.name = name;
   }
}
Run Code Online (Sandbox Code Playgroud)

然后将http调用的响应映射到您需要的对象:

getHeroes (): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl)
      .pipe(
        map(hero => new Hero(hero.id, hero.name),
        catchError(this.handleError('getHeroes', []))
      );
  }
Run Code Online (Sandbox Code Playgroud)