代码之家  ›  专栏  ›  技术社区  ›  K.Z

未定义的角度对象数组值引发错误

  •  2
  • K.Z  · 技术社区  · 6 年前

    我正在研究Angular6应用程序。我有输入的行为变量,一旦我收到数据,我就映射到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 回复  |  直到 6 年前
        1
  •  2
  •   howHighUR    6 年前

    尝试改变 if(survey!=null) if(!survey) return; . 看来你要回来了 undefined 如果没有 survey 原因返回语句在括号之外。如果它能工作,你需要检查这个对象的所有道具 未定义 . 此外,还需要向该对象添加键入内容。

    private mapSurveyInfo(survey:any):SurveyInfoDataModel{
        if (!survey) return;
    
        this.surveyInfo = new SurveyInfoDataModel(
          survey.consultationId,
          survey.surveyId,
          survey.surveyIdNum,
          survey.surveyName
        );  
    
        return this.surveyInfo;
    }
    
        2
  •  1
  •   Melchia    6 年前

    Survey 在您的情况下是未定义的。而不是测试如果 survey 为空,您可以使用以下命令测试两个未定义的空值:

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