Angular 5 模型 httpClient 类型转换

zan*_*rsh 0 httpclient models angular5

我在配料.model.ts 中声明了一个模型

export class Ingredient {
 constructor(private name: string, public amount: number) {}

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

在配料.service.ts 中,如果我以这种方式获取它们:

httpClient.get<Ingredient>(url).subscribe(
 (igredient) => {
   console.log(igredient.getName());
 });
Run Code Online (Sandbox Code Playgroud)

它在控制台中给出错误,例如“属性 igrient 中没有方法 getName”。

另外,每当我尝试声明属性类型 Category[] 时,它都会失败,但 Array 似乎工作正常。

编辑: 我想提供更多信息。

给定 Igredient 模型和以下 JSON 结构:

{
 name: "Apple",
 amount: "5",
 created_at: "date",
}
Run Code Online (Sandbox Code Playgroud)

Igredient 构造函数甚至没有被调用,因此 GET 有效负载不会被解析。

rea*_*rry 5

您需要使用属性,而不是方法。返回的对象实际上是一个 json 对象,并且没有“getName()”方法之类的东西(尽管您努力添加类型信息)。尝试这样的事情:

export interface Ingredient {
    strin: string,
    amount: number,
    created_at: string
}


httpClient.get<Ingredient>(url).subscribe(
     (igredient) => {
          console.log(igredient.amount);
});
Run Code Online (Sandbox Code Playgroud)

编辑:您需要根据预期的 json 对象提供类型信息。如果返回的 json 对象有属性、srin、amount、created_at,那么你需要定义一个与期望的 json 对象兼容的类型。