Angular2笔记7-http Posted on 2016-07-21 | In Angular2入门 | 这一部分在前端伪造了一个http服务, 然后按RestFul风格, 把增删改查重写了 前端http服务123456789import { InMemoryBackendService, SEED_DATA } from 'angular2-in-memory-web-api';import { InMemoryDataService } from './in-memory-data.service';//给AppComponent配置一个临时的http服务测试bootstrap(AppComponent, [ appRouterProviders, HTTP_PROVIDERS, { provide: XHRBackend, useClass: InMemoryBackendService }, // in-mem server { provide: SEED_DATA, useClass: InMemoryDataService } // in-mem server data]); 1234export class InMemoryDataService { //createDb什么的是http客户端提供的方法 createDb() { let heroes = [ ## *.server.ts12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import { Injectable } from '@angular/core';import { Headers, Http } from '@angular/http';import 'rxjs/add/operator/toPromise';import { Hero } from './hero';@Injectable()export class HeroService { private heroesUrl = 'app/heroes'; //URL前缀 constructor(private http: Http) { } getHeroes(): Promise<Hero[]> { return this.http.get(this.heroesUrl) .toPromise()//toPromise是第三方提供的 'rxjs/add/operator/toPromise'; .then(response => response.json().data) .catch(this.handleError); } getHero(id: number) { return this.getHeroes() .then(heroes => heroes.find(hero => hero.id === id)); } //自己封装一个saveOrUpdate save(hero: Hero): Promise<Hero> { if (hero.id) { return this.put(hero); } return this.post(hero); } delete(hero: Hero) { let headers = new Headers(); headers.append('Content-Type', 'application/json');//指定返回类型 let url = `${this.heroesUrl}/${hero.id}`; return this.http .delete(url, {headers: headers}) .toPromise() .catch(this.handleError); } // Add new Hero private post(hero: Hero): Promise<Hero> { let headers = new Headers({ 'Content-Type': 'application/json'}); return this.http .post(this.heroesUrl, JSON.stringify(hero), {headers: headers}) .toPromise() .then(res => res.json().data) .catch(this.handleError); } // Update existing Hero private put(hero: Hero) { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let url = `${this.heroesUrl}/${hero.id}`; return this.http .put(url, JSON.stringify(hero), {headers: headers}) .toPromise() .then(() => hero) .catch(this.handleError); } //错误处理 private handleError(error: any) { console.error('An error occurred', error); return Promise.reject(error.message || error); }}