Angular 角度:HttpClient服务和可观察的自定义类型

Angular 角度:HttpClient服务和可观察的自定义类型,angular,typescript,httpclient,Angular,Typescript,Httpclient,我的getheros函数应该返回Hero[]对象,但我无法访问它的方法。 我做错什么了吗 hero.ts export class Hero { id: number; name: string; getName(): string { return this.name; } } 英雄服务 getHeroes (): Observable<Hero[]> { return this.http.get<Hero[]>(this.heroe

我的
getheros
函数应该返回
Hero[]
对象,但我无法访问它的方法。 我做错什么了吗

hero.ts

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

  getName(): string {
    return this.name;
  }
}
英雄服务

getHeroes (): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl)
      .pipe(
        catchError(this.handleError('getHeroes', []))
      );
  }
我得到一个
错误类型ERROR:hero.getName不是最后一行的函数


下面是一个实时版本

Http调用返回一个对象(实际上只是一个JSON字符串,稍后将由HttpClient解析),该对象具有id和名称,没有函数。您可以在“网络”选项卡中进行检查

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

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

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

  contructor(id, name) {
    this.id = id;
    this.name = name;
   }
}
然后将http调用的响应映射到所需的对象:

getHeroes (): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl)
      .pipe(
        map(hero => new Hero(hero.id, hero.name),
        catchError(this.handleError('getHeroes', []))
      );
  }
getHeroes():可观察{
返回this.http.get(this.heroesUrl)
.烟斗(
地图(英雄=>新英雄(hero.id,hero.name),
catchError(this.handleError('getHeroes',[]))
);
}

Http调用返回一个id和名称都没有函数的对象(实际上只是一个JSON字符串,稍后由HttpClient解析)。您可以在网络选项卡中进行检查

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

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

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

  contructor(id, name) {
    this.id = id;
    this.name = name;
   }
}
然后将http调用的响应映射到所需的对象:

getHeroes (): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl)
      .pipe(
        map(hero => new Hero(hero.id, hero.name),
        catchError(this.handleError('getHeroes', []))
      );
  }
getHeroes():可观察{
返回this.http.get(this.heroesUrl)
.烟斗(
地图(英雄=>新英雄(hero.id,hero.name),
catchError(this.handleError('getHeroes',[]))
);
}

Hero应该是一个接口而不是类。请检查以下链接。@JeevaJsb为什么?当Hero是一个接口时,我仍然有一个错误事件。接口无法实例化。有关良好实践,请使用接口而不是类。有关实例化,请参阅@ritaj的answerHero应该是一个接口而不是类。请检查以下链接。@JeevaJsb为什么?当hero是一个接口时,我仍然有一个错误事件。接口无法实例化。为了获得良好的实践,请使用接口而不是类。对于实例化,请参考@ritaj的回答这将是答案。因为如果属性应该是可访问的,我们需要实例化类。这将是答案。因为我们需要实例化如果属性应该是可访问的,则初始化该类。