javascript - Angular valor de arreglo de objetos arroja error de indefinido
Estoy trabajando en una aplicación Angular 6. Tengo una variable de comportamiento de Input, una vez que recibo los datos, los asigno al objeto surveyInfo. Tengo la clase surveyInfoDataModel como se muestra a continuación; luego estoy intentando mostrar estos datos leyendo el objeto surveyInfo en la plantilla, pero ocurre un error.
error
ERROR TypeError: Cannot read property 'surveyId' of undefined
componente
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;
}
Clase de modelo de datos de información de encuesta
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;
}
}
plantilla HTML
<div class="surveyListInfoBlock">
<div *ngIf="surveyInfo">
{{surveyInfo.surveyId}}
</div>
</div>
Respuesta #1
Intenta cambiar if(survey!=null) a if(!survey) return;. Parece que vas a devolver undefined si no hay survey porque la instrucción return está fuera de los corchetes. Si funciona, necesitarás comprobar todas las propiedades de este objeto para ver si son undefined. También necesitas agregar tipado a este objeto.
private mapSurveyInfo(survey:any):SurveyInfoDataModel{
if (!survey) return;
this.surveyInfo = new SurveyInfoDataModel(
survey.consultationId,
survey.surveyId,
survey.surveyIdNum,
survey.surveyName
);
return this.surveyInfo;
}
Respuesta #2
Survey en tu caso está indefinido. En lugar de comprobar si survey es nulo, puedes comprobar tanto nulo como indefinido con esto:
if(!!survey){
this.surveyInfo = new SurveyInfoDataModel(
survey.consultationId,
survey.surveyId,
survey.surveyIdNum,
survey.surveyName
);
}
