HttpClient not running constructor

℡╲_俬逩灬. 提交于 2019-12-18 07:05:35

问题


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());
});

回答1:


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.

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

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

Something like this:

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

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




回答2:


var customerObservable: Observable<Customer> = 
    this.authHttp.get<Customer>(url)
    .map(res => {
         return new Customer()
     });

here you can also add/map properties from response to your new Customer() instance if you need to.



来源:https://stackoverflow.com/questions/46570775/httpclient-not-running-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!