I'm not able to exploit the data that i just fetched #Ionic3 #Http #DataIsUndefined


#1

Hey, i’m a complete beginner and i don’t understand what i’m doing wrong.

my component.html :

  <h2>Hello</h2>
  <h2>Your in "{{data[0].team_name}}"</h2>
  <div>Start at: {{data[0].start}}</div>
  <div>Stop at: {{data[0].stop}}</div>

my component.ts :

import { Component, OnInit } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController } from 'ionic-angular';
import { HttpProvider } from "../../providers/http/http";

export class CheckPage implements OnInit{

  data;

  ngOnInit():void{
    this.httpProvider.getJsonData()
      .subscribe(data => {
          this.data = data;
          console.log(this.data);
          return this.data;
        },
        err =>{
          console.error("Error : "+err);
        },
        () => {
          console.log('getData completed');
          console.log(this.data);
        }
      );
    console.log(this.data);
  };
}

my provider:

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';

@Injectable()
export class HttpProvider {

  constructor(public http: Http) {
    console.log('Hello HttpProvider Provider');
  }

  getJsonData(){
    return this.http.get('../../assets/data/data.json').map(res => res.json());
  }

}

In my console i have an array with all the data that i just fetched:

[…]
0: Object { id: 1, company_name: “Condo”, address: “213 Grove Street”, … }
1: Object { id: 2, company_name: “Ikea”, address: “213 Ikea Street”, … }
2: Object { id: 3, company_name: “McDo”, address: “213 McDo Street”, … }
length: 3
proto: Array []

plus a error message :

TypeError: _co.data is undefined


#2

Same issue probably as this one


#3

Thanks but it’s not helping, i think that it’s a “timing” problem, my page is loaded before that my http call is completed. How can i fix that ?


#4

Hey there!

Have you tried angular’s safe navigation operator?
If that doesn’t work try using a *ngIf to check if your data has some content in it


#5

Hey,

Thanks, *ngIf gets rid of the error message, i get now my 3 raw [object, Object] printed on my page


#6

Try giving a type to your data, something like:

data: any;

#7

Pretty sure it is exactlly the same issue, either to be resolved through instantiating a default value in the constructor, using ngIf or the elvis operator ?

Check the great instruction on template binding on angular.io


#8

Thanks data: any[]; + *ngIf worked just fine


#9

Glad I could help, cheers.