Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data from JSON with Angular2 Promise

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?

like image 529
smartmouse Avatar asked Oct 18 '22 02:10

smartmouse


1 Answers

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.

like image 185
smartmouse Avatar answered Oct 31 '22 11:10

smartmouse