问题
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