使用Angular2 Promise从JSON获取数据

时间:2016-09-05 08:54:40

标签: json http angular angular-promise angular2-services

我试图从Angular2文档中的http tutorial之后的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);
}

组件:

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

型号:

export class Hero {
  constructor(
    public id: number,
    public name: string,
    public power: string,
    public alterEgo?: string
  ) {  }
}

我将private heroesUrl = 'app/heroes';替换为我的端点,该端点是JSON文件(private heroesUrl = 'app/mockups/heroes.json';),其中包含根据hero模型的数据。

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

1 个答案:

答案 0 :(得分:2)

解决方案是JSON对象必须以具有相同名称pattern.test(myString)的属性开头。

将第一个属性重命名为response.json().data可以完成这项任务。

相关问题