2017-10-04 74 views
0

我使用HttpClient从json端点获取对象。在我获取它并订阅observable之后,我发现构造函数不能在模型上运行,并且对象上的公共方法都未定义。如何让构造函数运行并且方法可用?HttpClient未运行构造函数

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

回答

3

你正在从不用彷徨返回的数据是在客户类的形状(假设你有未显示的属性)。但实际上并不是您的客户类的实例

这就是您无法访问任何Customer类方法的原因。

您必须使用关键字new创建客户实例,然后将get中的数据复制到其中。

事情是这样的:

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

你,然后创建客户的新实例,你的构造函数将被执行。

+0

为什么不只是''让customerInstance = new Customer(customerResponse);''' – Sonicd300

+0

是的,这是做到了。这与c#中的AutoMapper类似。 – Darthg8r

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

在这里你还可以从响应添加/地图属性你new Customer()例如,如果你需要。

相关问题