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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With