2017-12-07 7 views
1

のプロパティを読み取ることができませんが、双方向バインディング - ネストされたオブジェクト - 角度は - 私は、ネストされたオブジェクトに対して、[(ngModel)]を使用したい未定義

Cannot read property 'mxn' of undefined

私にエラーを与えているこれらは私のモデルのデータ構造:

company.model.ts

import Currency from './currency.model'; 

class Company { 
_id: string; 
name: string; 
maxLimit: number; 
source: [string]; 
deliveryMethod: [string]; 
currency: Currency; 
date: Date; 

constructor() { 
    this.name = ''; 
    this.date = new Date(); 
    this.maxLimit = 0; 
    this.source = ['']; 
    this.deliveryMethod = ['']; 
    this.currency.mxn = 0; 
    this.currency.php = 0; 
    } 
} 

export default Company; 

currency.model.ts

class Currency { 
mxn: number; 
php: number; 


constructor() { 
    this.mxn = 0; 
    this.php = 0; 
} 
} 

export default Currency; 

、これは私がちょうど使用してmxn値を表示することができるよcompany.ts HTMLページ内の

public newCompany: Company = new Company(); 
companiesList: Company[]; 
editcompanies: Company[] = []; 

とHTML

の一部です:

<tr class="companies" *ngFor="let company of companiesList"> 
{{company.currency.mxn}} 

が、私はngModel双方向バインディングを使用して値を更新し、それをデータベースに送信したいときは機能しません。

[(ngModel)] = "newCompany.currency.mxn" 上記のエラーが発生します。 私が [(ngModel)] = "newCompany.currency"を使用している場合、それは私にエラーを与えませんが、私はmxnに値を割り当てることができないので、コードは役に立たないです。

私は[(ngModel)] = "newCompany.name"とうまく動作し、名前を更新できると言わなければなりません。

郵便配達員と一緒に試してみると、バックエンドがうまく動作します。問題は角度側です。

私のデータ構造が正しいかどうかは疑問です。ネストされたオブジェクトに対して双方向バインディングを使用するにはどうすればよいですか?あなたの会社のモデルで

+0

まず、通貨メンバーを会社クラスのコンストラクタでインスタンス化しないでください。 –

+0

ありがとう、あなたはすべて正しいです。それは単に通貨をインスタンス化することによって働いた。 – Milad

答えて

1
currency: Currency; 
... 
constructor() { 
    ... 
    this.currency.mxn = 0; 
    this.currency.php = 0; 
} 

MXNとPHPはまだ存在していません。原因を働いていない自分であなたが想定しnewCompanyをインスタンス化するときインスタンスcurrencyはnullです。プロパティーは含まれていません。

currency: Currency; 
... 
constructor() { 
    ... 
    this.currency = new Currency(); // invoke Currency constructor, create mxn and php with value 0, therefore you dont need this.currency.mxn = 0 and same to php 
} 
1

わずかな変化は十分なはずです:

class Company { 
 
    _id: string; 
 
    name: string; 
 
    maxLimit: number; 
 
    source: [string]; 
 
    deliveryMethod: [string]; 
 
    currency: Currency = new Currency(); // provide an instance, otherwise this field will be undefined 
 
    date: Date; 
 

 
    constructor() { 
 
     this.name = ''; 
 
     this.date = new Date(); 
 
     this.maxLimit = 0; 
 
     this.source = ['']; 
 
     this.deliveryMethod = ['']; 
 
     this.currency.mxn = 0; 
 
     this.currency.php = 0; 
 
     } 
 
    } 
 

 
export default Company;

1

あなたのコンストラクタで通貨フィールドをインスタンス化していないように見えます。おそらくあなたのバックエンドは、あなたのためにそれらをインスタンス化し(私はここで推測している)ので、それはおそらくあなたのcompaniesListで働いている

currency = new Currency(); 

currency: Currency; 

を変更することで、試してみてください。そして、あなたは、私はそれはあなたがCurrencyのインスタンスをインスタンス化するまで行方不明new Currency()

関連する問題