如何初始化OnInit中定义的嵌套对象? Angular2

时间:2017-07-27 07:49:54

标签: angular object nested

所以我一直收到这个错误" TypeError:无法读取属性' otherDocumentaryEvidence'未定义"。我知道我需要以某种方式初始化这个对象,但我不确定这个过程。我的理解是在ngOnInit阶段从模板服务

定义对象
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;
}

在我的组件代码中,我在构造函数中初始化Share Case对象和otherDocumentaryEvidence对象,如下所示:

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

但我仍然得到同样的错误?我不确定为什么会这样。我的模板中调用此对象的行也如下所示

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

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

您错过了*ngIf

中的其他支票
<div *ngIf='shareCase && 
            shareCase.case && 
            shareCase.case.otherDocumentaryEvidence && 
            shareCase.case.otherDocumentaryEvidence.length > 0'> 

您缺少shareCase.case支票

答案 1 :(得分:1)

尝试添加null / undefined check的问号。

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