2017-10-04 115 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()例如,如果你需要。

相關問題