我正在研究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>
答案 0 :(得分:2)
尝试将if(survey!=null)
更改为if(!survey) return;
。如果没有undefined
,因为return语句不在括号内,您似乎将返回survey
。如果可行,则需要在undefined
上检查该对象的所有道具。另外,您需要为此对象添加类型。
private mapSurveyInfo(survey:any):SurveyInfoDataModel{
if (!survey) return;
this.surveyInfo = new SurveyInfoDataModel(
survey.consultationId,
survey.surveyId,
survey.surveyIdNum,
survey.surveyName
);
return this.surveyInfo;
}
答案 1 :(得分:1)
Survey
未定义。除了测试survey
是否为null之外,您还可以使用以下方法测试null和undefined:
if(!!survey){
this.surveyInfo = new SurveyInfoDataModel(
survey.consultationId,
survey.surveyId,
survey.surveyIdNum,
survey.surveyName
);
}