2017-10-04 2 views
0

私はHttpClientを使用してjsonエンドポイントからオブジェクトを取得しています。私がオブジェクトを取得してオブザーバブルに登録した後、コンストラクタがモデルで実行されず、オブジェクトのパブリックメソッドがすべて定義されていないことがわかりました。コンストラクタを実行するにはどのようにしてメソッドを使用できますか?コンストラクタを実行していない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

あなたがに.getから返さ取得されたデータは、あなたの顧客クラス(あなたが示されていない性質を持っていると仮定)の形状です。実際にはお客様のクラスのインスタンスではありません。

これは、どのようなCustomerクラスメソッドにもアクセスできないためです。

newキーワードを使用してCustomerインスタンスを作成し、getからそのデータをコピーする必要があります。このような

何か:

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

あなたは、顧客の新しいインスタンスを作成しているし、あなたのコンストラクタが実行されます。

+0

なぜか '' 'let ''だけではなく、customerInstance = new Customer(customerResponse);' '' – Sonicd300

+0

これでやったよ。これはC#のAutoMapperに似ています。 – Darthg8r

0

ここでは、必要に応じてnew Customer()インスタンスに応答のプロパティを追加/マップすることもできます。

関連する問題