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:
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?
source share