5

I'm trying to get data from a JSON file following the http tutorial from the Angular2 documentation:

Service:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';

private heroesUrl = 'app/heroes';  // URL to web api

constructor(private http: Http) { }

getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
        .toPromise()
        .then(response => response.json().data as Hero[])
        .catch(this.handleError);
}

Component:

import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';

@Component({
  selector: 'my-app',
  template: // some template,
  styles: // some style,
  providers: [HeroService]
})

export class AppComponent implements OnInit {
  title = 'Tour of Heroes';
  heroes: Hero[];

  constructor(private heroService: HeroService) { }

  getHeroes(): void {
    this.heroService.getHeroes().then(heroes => {
        this.heroes = heroes;
        console.log('heroes', this.heroes);
    });
  }

  ngOnInit(): void {
    this.getHeroes();
  }
}

Model:

export class Hero {
  constructor(
    public id: number,
    public name: string,
    public power: string,
    public alterEgo?: string
  ) {  }
}

I replaced private heroesUrl = 'app/heroes'; with my endpoint that is a JSON file (private heroesUrl = 'app/mockups/heroes.json';), that contains data according to hero model.

But when i run my app i get no data and there is any error message. Isn't my code correct?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
smartmouse
  • 13,912
  • 34
  • 100
  • 166
  • Where do you not get data? Can you please add a `console.log(data);` in the code in your question where you expect `data` (or whatever name) you expect to have a value? – Günter Zöchbauer Sep 05 '16 at 09:20
  • Where can i add `console.log(data)`? – smartmouse Sep 05 '16 at 09:29
  • I don't understand the question. Where do you expect what variable to have a value? To debug it you can add a `console.log(...)` line. This allows you to investigate yourself and allows us to see what you expect. I can't answer your question when I don't know what you expect to happen. – Günter Zöchbauer Sep 05 '16 at 09:33
  • I expect to have data in `heroes` variable. How to add `console.log(data)` in `getHeroes()` function? – smartmouse Sep 05 '16 at 09:49
  • I updated your question. Is that where you want the value? – Günter Zöchbauer Sep 05 '16 at 09:54
  • Thank you for your edit. I get `undefined`. – smartmouse Sep 05 '16 at 10:15
  • What do you get when you return `.data` from `response.json().data`? – Günter Zöchbauer Sep 05 '16 at 10:20
  • I don't know. Do you know any way to add a `console.log` there? – smartmouse Sep 05 '16 at 10:21
  • Keep `console.log()` where it is and just remove `.data`. – Günter Zöchbauer Sep 05 '16 at 10:22
  • It fails on `*NgFor` that i use in the template file for cycling on JSON elements. `EXCEPTION: Error in http://localhost:3000/app/components/app.component.js class AppComponent - inline template:0:285 caused by: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.` – smartmouse Sep 05 '16 at 10:33
  • What does `console.log()` print? – Günter Zöchbauer Sep 05 '16 at 10:34
  • It prints what i pasted above. It prints even the following error: `ORIGINAL EXCEPTION: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.` – smartmouse Sep 05 '16 at 10:36
  • That's an error caused by `*ngFor` not the output of `console.log()`. The output of `console.log()` should have been printed before the error you posted. – Günter Zöchbauer Sep 05 '16 at 10:38
  • Yes, you are right. That error has been printed after the `console.log()` output. Anyway the output is `undefined`. – smartmouse Sep 05 '16 at 11:48
  • If the output is still undefined than this means that the response from the server didn't contain any data. Actually I don't believe it is undefined. If `*ngFor` complains about an object, than it didn't get `undefined`. Also `[object Object]` in the error message indicates that it got an object (!= `undefined`) – Günter Zöchbauer Sep 05 '16 at 11:53
  • 6
    I solved. The problem was that the JSON object must start with a property that has the same name of `response.json().data`. So i renamed the first property to `data`. Please upvote this comment so other members can see it. – smartmouse Sep 05 '16 at 12:09
  • Is there 'data' field in your json file? Try using angular filter {{Hero | json}} wherever you are trying to access Hero object in your html, just to check if it has data. – veena Dec 19 '16 at 04:15
  • @smartmouse your comment helped me a lot. Why don't you answer the question? – Vincenzo Aug 07 '17 at 09:47
  • @Vincenzo Done, thank you! So, now you can upvote it :D – smartmouse Aug 11 '17 at 18:16

1 Answers1

3

The solution is that the JSON object must start with a property that has the same name of response.json().data.

Renaming the first property to data does the job.

smartmouse
  • 13,912
  • 34
  • 100
  • 166