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

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

问题描述

我在Ingredient.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.

修改: 我想提供更多信息.

I want to provide more info.

给出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天全站免登陆