小编Hss*_*sen的帖子

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

我的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链接

httpclient typescript angular

0
推荐指数
1
解决办法
223
查看次数

标签 统计

angular ×1

httpclient ×1

typescript ×1