简体   繁体   中英

Angular object array value throw error of undefined

I am working on Angular 6 application. I have behaviour variable of Input, once I received data, I map to surveyInfo object. I have surveyInfoDataModel class as shown below; followed by I am trying to display this data by reading surveyInfo object in template but go error

error

ERROR TypeError: Cannot read property 'surveyId' of undefined

component

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;
}

Survey Info DataModel class

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 template

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

Try to change if(survey!=null) to if(!survey) return; . Looks like you going to return undefined if there is no survey cause return statement is outside the brackets. If it will work, you'll need to check all props of this object on undefined . Also you need to add typing to this object.

private mapSurveyInfo(survey:any):SurveyInfoDataModel{
    if (!survey) return;

    this.surveyInfo = new SurveyInfoDataModel(
      survey.consultationId,
      survey.surveyId,
      survey.surveyIdNum,
      survey.surveyName
    );  

    return this.surveyInfo;
}

Survey in your case is undefined. Instead of testing if survey is null you can test for both null & undefined with this:

 if(!!survey){
  this.surveyInfo = new SurveyInfoDataModel(
    survey.consultationId,
    survey.surveyId,
    survey.surveyIdNum,
    survey.surveyName
  );  
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM