HttpClient没有运行构造函数 [英] HttpClient not running constructor

查看:85
本文介绍了HttpClient没有运行构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HttpClient从json端点获取对象.提取并订阅可观察对象后,我发现构造函数未在模型上运行,并且对象上的公共方法都未定义.如何使构造函数运行并且方法可用?

I'm fetching an object from a json endpoint using the HttpClient. After I fetch it and subscribe to the observable, I found that the constructor doesn't run on the model and the public methods on the object are all undefined. How do I get the constructor to run and the methods are available?

export class Customer {

    constructor() {
        this.Addresses = new Array<Address>();
        }

    public Addresses: Array<Address>;

    public addAddress(address: Address) void{
        this.Addresses.push(address);
    }
}

var url: string = `${this.urlBase}api/customer/${id}`;
var customerObservable: Observable<Customer> = this.authHttp.get<Customer>(url);

customerObservable.subscribe(customer => {
    // Addresses is undefined!
    customer.Addresses.push(new Address());
    // addAddress is undefined!
    customer.addAddress(new Address());
});

推荐答案

从.get返回的数据位于Customer类的 shape 中(假设您拥有的属性不是如图所示).但实际上不是您的Customer类的实例.

The data you are getting returned from the .get is in the shape of your Customer class (assuming you have properties that are not shown). But is not actually an instance of your Customer class.

这就是为什么您无法访问任何Customer类方法的原因.

That is why you can't access any of the Customer class methods.

您必须使用new关键字创建一个Customer实例,然后将get中的数据复制到其中.

You'd have to create a Customer instance using the new keyword and then copy the data from the get into it.

类似这样的东西:

let customerInstance = Object.assign(new Customer(), customer);

然后您将创建一个新的客户实例,您的构造函数将执行.

You are then creating a new instance of the customer and your constructor will execute.

这篇关于HttpClient没有运行构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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