gpt4 book ai didi

javascript - Angular 对象数组值抛出未定义的错误

转载 作者:搜寻专家 更新时间:2023-10-30 21:26:29 25 4
gpt4 key购买 nike

我正在开发 Angular 6 应用程序。我有输入的行为变量,一旦我收到数据,我就会映射到 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,您将返回 undefined,因为 return 语句在括号之外。如果它能工作,你需要在 undefined 上检查这个对象的所有属性。您还需要向该对象添加类型。

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

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

return this.surveyInfo;
}

关于javascript - Angular 对象数组值抛出未定义的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54459381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com