Angular 5 模型 httpClient 类型转换 [英] Angular 5 models httpClient type casting

查看:24
本文介绍了Angular 5 模型 httpClient 类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在成分.model.ts中声明了一个模型

I declare a model in ingredient.model.ts

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

 getName() { return this.name }
}

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

In ingredients.service.ts, if I get them in this way:

httpClient.get<Ingredient>(url).subscribe(
 (igredient) => {
   console.log(igredient.getName());
 });

它在控制台中给出错误,例如属性 igredient 中没有方法 getName".

It gives errors in console, such as "no method getName in property igredient".

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

Also, whenever I try to declare a property type Category[] it fails, but Array seems working fine.

我想提供更多信息.

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

Given the Igredient model and the following JSON structure:

{
 name: "Apple",
 amount: "5",
 created_at: "date",
}

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

The Igredient constructor isn't even invoked, therefore the GET payload won't be parsed.

推荐答案

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

You'll need to use a property, not a method. The returned object is really a json object, and there is no such thing as "getName()" method (despite your effort to add a type information). Try something like this:

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


httpClient.get<Ingredient>(url).subscribe(
     (igredient) => {
          console.log(igredient.amount);
});

您需要根据预期的 json 对象提供类型信息.如果返回的json对象有属性,strin,amount,created_at,那么就需要定义一个与期望json对象兼容的类型.

You need to provide a type information based on the expected json object. If the returned json object has attributes, strin, amount, and created_at, then you need to define a type that is compatible with the expected json object.

这篇关于Angular 5 模型 httpClient 类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆