Angular2笔记7-http

这一部分在前端伪造了一个http服务, 然后按RestFul风格, 把增删改查重写了

前端http服务

1
2
3
4
5
6
7
8
9
import { 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
]);
1
2
3
4
export class InMemoryDataService {
//createDb什么的是http客户端提供的方法
createDb() {
let heroes = [

## *.server.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { 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);
}
}