I am printing an object dateImagen.boolean
and I get an error that Cannot read property 'boolean' of undefined
I do console.log(dateImagen)
, but if I get the information that is this:
Object {boolean: true, result: Array(2), mensaje: "Hay imagen"}
but when I print {{dateImagen.boolean}}
it I get that message that boolean is undefined and if {{dateImagen}}
I print it, it prints everything out like this:
[Object, Object]
I made a JSON.stringify(dateImagen)
and print it and I get the object as it is but in string. Do you know if I'm doing something wrong? I'm practicing ionic2 doing a personal project. Thank you very much, this is the code I do:
images.ts
export interface Images{
boolean: boolean,
result: any,
mensaje: string
}
contentImages.ts
import { Component, Input } from '@angular/core';
import { Images } from '../../app/commons/imagenes';
import { contenidoServices } from '../../app/services/contenidos';
@Component({
selector: 'contenido-images',
templateUrl: 'contenidoImages.html'
})
export class contenidoImage{
dateImagen:Images;
@Input() id: number;
constructor(private contenido: contenidoServices){
}
ngOnInit(){
let idContenido = this.id;
let imagenesContenido = this.contenido.getContenidoImagenes(idContenido);
imagenesContenido.subscribe((res)=>{
let date = {
boolean: (res == 2) ? false : true,
result: res,
mensaje: (res == 2) ? 'No hay imagen' : 'Hay imagen'
}
this.dateImagen = date;
console.log(this.dateImagen);
},(err) => {
console.log(err);
});
}
}
contentImages.html
<div>
{{dateImagen.boolean}}
</div>
Try the following:
note the use of
?
elvis operator.You have and make use of this
{{dateImagen.boolean}}
in the view but there is a time until the subscription is complete, in which it is null.Specifying a
?
between the object and the property{{dateImagen?.boolean}}
ensures that it is defined before evaluating the union, could be understood as safe navigation .When this value resolves the union it will be updated by Angular's change tracking.
PS: I haven't tested your code but based on your error and what you comment, it is possible that what is mentioned in this answer is what you are looking for.
Uses:
However, I recommend that before using the object,
dateImagen
always check that the object is notNULL
orundefined
.Example: