簡體   English   中英

角對象數組值拋出錯誤未定義

[英]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;

 }
}

html模板

<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM