2017-07-27 69 views
0

所以我不斷收到這個錯誤「TypeError:無法讀取未定義的屬性」otherDocumentaryEvidence「。我知道我需要初始化這個對象,但我不確定這個過程。我的理解是,對象被在ngOnInit階段從模板服務定義如何初始化在OnInit中定義的嵌套對象? Angular2

ngOnInit(): void { 
    this._templateService 
     .getTemplateSnapshot(this.template) 
     .responseData() 
     .subscribe(templateSnapStream => { 
      return this.shareCase = templateSnapStream.result; 
     }) 
} 

我的目標看起來像這樣

export class ShareCase { 
    shareCaseReason?: string; 
    caseDetails?: ICasedeit; 
    involvedPersonsAndOrganisations?: IInvolved; 
    policeOfficer?: IPolice; 
    incidents?: IIncident; 
    offences?: IOffence; 
    suspect?: ISuspectDetails 
    witnessStatements?: IStatements; 
    interviewNotes?: IIncident; 
    notebookEntries?: INotebook; 
    victims?: IVictim; 
    witnesses?: IWitness; 
    physicalEvidence?: IEvidence; 
    otherDocumentaryEvidence?: IDocEvidence; 
} 

在我的組件的代碼,我初始化無論是分享案例對象和otherDocumentaryEvidence對象在像這樣的構造函數中:

this.shareCase = new ShareCase(); 
this.shareCase.otherDocumentaryEvidence = new IDocEvidence(); 

但是我仍然得到相同的錯誤?我不確定這是爲什麼。在我的模板中調用此對象的行也看起來像這樣

<div *ngIf='shareCase && shareCase.case.otherDocumentaryEvidence && shareCase.case.otherDocumentaryEvidence.length > 0'> 

任何幫助將不勝感激!

回答

1

你缺少額外的檢查,在你*ngIf

<div *ngIf='shareCase && 
      shareCase.case && 
      shareCase.case.otherDocumentaryEvidence && 
      shareCase.case.otherDocumentaryEvidence.length > 0'> 

你缺少shareCase.case檢查

+0

魔法!非常感謝! –

+0

高興地幫助你 – Aravind

1

嘗試增加對空/未定義檢查問號。

<div *ngIf='shareCase && shareCase.case?.otherDocumentaryEvidence && shareCase.case?.otherDocumentaryEvidence.length > 0'>