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

查看:32
本文介绍了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天全站免登陆