使用Angular2 Promise从JSON获取数据

sma*_*use 5 json http angular-promise angular2-services angular

我正在尝试从Angular2文档中的http教程之后从JSON文件中获取数据:

服务:

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);
}
Run Code Online (Sandbox Code Playgroud)

零件:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

模型:

export class Hero {
  constructor(
    public id: number,
    public name: string,
    public power: string,
    public alterEgo?: string
  ) {  }
}
Run Code Online (Sandbox Code Playgroud)

private heroesUrl = 'app/heroes';用我的端点替换了JSON文件(private heroesUrl = 'app/mockups/heroes.json';),它包含根据hero模型的数据.

但是当我运行我的应用程序时,我没有数据,并且有任何错误消息.我的代码不正确吗?

sma*_*use 3

解决方案是 JSON 对象必须以同名的属性开头response.json().data

将第一个属性重命名为即可data完成这项工作。