Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient not running constructor

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());
});
like image 825
Darthg8r Avatar asked Oct 04 '17 17:10

Darthg8r


2 Answers

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.

like image 186
DeborahK Avatar answered Sep 19 '22 11:09

DeborahK


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.

like image 33
dee zg Avatar answered Sep 20 '22 11:09

dee zg