Get data from JSON using Angular2 Promise

I am trying to get data from a JSON file after the http tutorial from the Angular2 documentation:

Services:

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'; its endpoint, which is a JSON file ( private heroesUrl = 'app/mockups/heroes.json'; ) that contains data according to the hero model.

But when I run my application, I do not receive any data and an error message appears. Is my code correct?

+5
source share
1 answer

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

Renaming the first property to data does the job.

+2
source

All Articles