角对象数组值抛出错误未定义

时间:2019-01-31 11:17:16

标签: javascript angular typescript angular6

我正在研究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;

 }
}

html模板

<div class="surveyListInfoBlock">
 <div *ngIf="surveyInfo">
   {{surveyInfo.surveyId}}
 </div>
</div> 

2 个答案:

答案 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
  );  
 }