Objecto undefined

3

I am printing an object dateImagen.boolean and I get an error that the 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}} I get that message that boolean is undefined and if I print it {{dateImagen}} if it prints everything coming out like this:

[Object, Object]

I did a JSON.stringify(dateImagen) and I printed 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:

imagenes.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>
    
asked by Albert Arias 07.04.2017 в 18:33
source

2 answers

3

Try the following:

<div>
  {{dateImagen?.boolean}}
</div>

Notice the use of ? elvis operator.

You have and make use of this {{dateImagen.boolean}} in the view but there is a time until the subcription is completed, in which it is null.

Specifying a ? between the object and the {{dateImagen?.boolean}} property ensures that it is defined before evaluating the union, it could be understood as a secure navigation .

When this value resolves the union will be updated by the change control of Angular.

P.D: I have not tried your code but according to your error and what you are commenting, it is possible that what is mentioned in this answer is what you are looking for.

    
answered by 07.04.2017 / 21:57
source
0

Use:

console.log(dateImagen.boolean);

Anyway, I recommend that before using the object dateImagen always verify that the object is not NULL or undefined .

Example:

// Solo se mostrará información si el objeto no es NULL o undefined:
if (dateImagen != null || dateImagen != undefined) {    
    console.log(dateImagen.boolean);
}
    
answered by 07.04.2017 в 18:51