Open ChuangPoPO opened 7 years ago
app.moudule.ts
import { HttpModule } from '@angular/http';
imports : [...]
Simulate the web API:InMemoryWebApiModule
in-memory-data.service.ts replace mock-heroes.ts
src/app/hero.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';
private heroesUrl = 'api/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);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
.toPromise
將 Observable 轉為 Promise,但 Observable 本身沒有這功能,所以要 import 'rxjs/add/operator/toPromise';
.then(response => response.json().data as Hero[])
用 .then
取得資料,使用 HTTP Response 的 .json()
方法取得資料.catch(this.handleError);
getHero(id: number): Promise<Hero> {
const url = `${this.heroesUrl}/${id}`;
return this.http.get(url)
.toPromise()
.then(response => response.json().data as Hero)
.catch(this.handleError);
}
In this page, you'll make the following improvements.
You'll teach the app to make corresponding HTTP calls to a remote server's web API.