如何在angular 2 typescipt中的导出变量中传递Web Service

时间:2017-03-02 12:11:10

标签: angular typescript angular2-routing

我需要传递从导出var HEROES:Hero [] 函数中的服务器获取的JSON数据

链接是 https://angular.io/resources/live-examples/toh-5/ts/eplnkr.html

转到 app / mock-heroes.ts ,该文件包含以下数据,

import { Hero } from './hero';

export var HEROES: Hero[] = [
  {id: 11, name: 'Mr. Nice'},
  {id: 12, name: 'Narco'},
  {id: 13, name: 'Bombasto'},
  {id: 14, name: 'Celeritas'},
  {id: 15, name: 'Magneta'},
  {id: 16, name: 'RubberMan'},
  {id: 17, name: 'Dynama'},
  {id: 18, name: 'Dr IQ'},
  {id: 19, name: 'Magma'},
  {id: 20, name: 'Tornado'}
];

我需要从服务器获取此数据而不使用静态数据。我怎样才能实现它。

我已经使用以下代码

获取了数据服务
private serviceUrl = "http://localhost:9000/service";

getServiceOne(): Observable<Track[]> {
  this.http.get(this.serviceUrl)
      .map(res => res.json());

}

输出

[
  {id: 11, name: 'Mr. Nice'},
  {id: 12, name: 'Narco'},
  {id: 13, name: 'Bombasto'},
  {id: 14, name: 'Celeritas'},
  {id: 15, name: 'Magneta'},
  {id: 16, name: 'RubberMan'},
  {id: 17, name: 'Dynama'},
  {id: 18, name: 'Dr IQ'},
  {id: 19, name: 'Magma'},
  {id: 20, name: 'Tornado'}
]

只需将上述数据解析为导出var HEROES:Hero []

我怎样才能做到这一点。我是打字稿的新手,我花了3天时间寻找输出但没有结果。

1 个答案:

答案 0 :(得分:0)

如果后端有Web api,您可以从服务器获取英雄。如果没有,那么你可以像文档中描述的那样模拟web api。有关详细信息,请参阅Simulating the web API

getHeroes(): Promise<Hero[]> {
  return this.http.get(this.heroesUrl)
           .toPromise()
           .then(response => response.json().data as Hero[])
           .catch(this.handleError);

如果您不想使用promises,那么您可以使用您需要订阅的Rxjs Observables来获取数据。

getHeroes(): Observable<Hero[]> {
  return this.http
           .get('app/heroes')
           .map(response => response.json().data as Hero[]);

和组件

this._heroService
    .getHeroes()      
    .subscribe(h => this.HEROES = h)