簡體   English   中英

如何在angular 2打字稿的導出變量中傳遞Web Service

[英]How can I pass Web Service inside export variable in angular 2 typescript

我需要在導出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天時間尋找輸出信息,但沒有結果。

如果后端具有Web api,則可以從服務器獲取英雄。 如果沒有,那么您可以像文檔中所述模擬Web API。 有關更多信息,請參見模擬Web API

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

如果您不想使用Promise,則可以使用需要訂閱以獲取數據的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM