2016-09-05 21 views
5

Próbuję pobrać dane z pliku JSON następstwie http tutorial z dokumentacją Angular2:pobrać dane z JSON z Angular2 Obietnicy

Usługa:

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); 
} 

Składnik:

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 
) { } 
} 

Wymieniłem private heroesUrl = 'app/heroes'; z mojego punktu końcowego, który jest plik JSON (private heroesUrl = 'app/mockups/heroes.json';), który zawiera dane według hero modelu.

Po uruchomieniu aplikacji nie otrzymuję żadnych danych i pojawia się komunikat o błędzie. Czy mój kod nie jest poprawny?

+0

Gdzie nie masz danych? Czy możesz dodać 'console.log (dane);' w kodzie w pytaniu, w którym spodziewasz się, że 'dane' (lub jakaś nazwa) będzie miała wartość? –

+0

Gdzie mogę dodać 'console.log (dane)'? – smartmouse

+0

Nie rozumiem pytania. Gdzie spodziewacie się, która zmienna ma wartość? Aby go zdebugować, możesz dodać linię 'console.log (...)'. Pozwala to zbadać samego siebie i pozwala zobaczyć, czego się spodziewasz. Nie mogę odpowiedzieć na twoje pytanie, gdy nie wiem, czego się spodziewać. –

Odpowiedz

2

Rozwiązaniem jest to, że obiekt JSON musi rozpoczynać się od właściwości o tej samej nazwie, co response.json().data.

Zmiana nazwy pierwszej nieruchomości na data wykonuje zadanie.

Powiązane problemy