2017-12-07 1 views
1
정의되지 않은

의 속성을 읽을 수 없습니다, 이들을 있습니다 내 모델의 데이터 구조 :양방향 바인딩 - 중첩 된 객체 - 각도를 - 나는 [(ngModel)]을 중첩 된 객체에 대해,하지만 나에게 오류</p> <p><code>Cannot read property 'mxn' of undefined</code></p> <p>을주고있다 사용할

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; 

이이 company.ts

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

난 그냥 사용하여 mxn 값 보여줄 수있어 HTML 페이지의 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의 원인을 작동하지 않는 당신이 Currency의 인스턴스를 인스턴스화 할 때까지 PHP는 아직 존재하지 않는 스스로 않습니다. 인스턴스 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: Currency; 

currency = new Currency(); 

에 변경하여보십시오. 인스턴스화 때 나는 당신을 가정합니다 newCompany는 누락 된 new Currency()

관련 문제