[英]Angular object array value throw error of undefined
我正在開發Angular 6應用程序。 我有Input的行為變量,一旦接收到數據,就映射到SurveyInfo對象。 我有SurveyInfoDataModel類,如下所示; 其次我試圖通過讀取模板中的SurveyInfo對象來顯示此數據,但是出錯
ERROR TypeError: Cannot read property 'surveyId' of undefined
export class MyComponent implements OnInit {
@Input() surveySelectedToGetInfo: BehaviorSubject<any>;
ngOnInit() {
this.surveySelectedToGetInfo.subscribe(surveyDataItem=>{
debugger;
if(surveyDataItem!=null){
this.loadSurveyInformation(surveyDataItem);
}
});
}
private loadSurveyInformation(selectedSurveyObject:any):any{
var mappedObject = this.mapSurveyInfo(selectedSurveyObject);
}
private mapSurveyInfo(survey:any):SurveyInfoDataModel{
if(survey!=null){
this.surveyInfo = new SurveyInfoDataModel(
survey.consultationId,
survey.surveyId,
survey.surveyIdNum,
survey.surveyName
);
}
return this.surveyInfo;
}
export class SurveyInfoDataModel{
surveyId:string;
surveyIdNum:string;
surveyName:string;
consultationId:string;
constructor(consultationId, surveyId, surveyIdNum, surveyName ){
this.consultationId =consultationId;
this.surveyId = surveyId;
this.surveyIdNum = surveyIdNum;
this.surveyName = surveyName;
}
}
<div class="surveyListInfoBlock">
<div *ngIf="surveyInfo">
{{surveyInfo.surveyId}}
</div>
</div>
嘗試將if(survey!=null)
更改為if(!survey) return;
。 看起來如果沒有survey
原因return陳述不在括號內,您將返回undefined
。 如果可行,則需要在undefined
上檢查該對象的所有道具。 另外,您需要向該對象添加類型。
private mapSurveyInfo(survey:any):SurveyInfoDataModel{
if (!survey) return;
this.surveyInfo = new SurveyInfoDataModel(
survey.consultationId,
survey.surveyId,
survey.surveyIdNum,
survey.surveyName
);
return this.surveyInfo;
}
您的情況下的Survey
是不確定的。 取而代之的測試,如果survey
是零,您可以測試兩個空與未定義與此:
if(!!survey){
this.surveyInfo = new SurveyInfoDataModel(
survey.consultationId,
survey.surveyId,
survey.surveyIdNum,
survey.surveyName
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.