commit | author | age
|
a5a648
|
1 |
import { Injectable } from '@angular/core'; |
W |
2 |
import { Http, Headers, Response, Request, RequestMethod, RequestOptions } from '@angular/http'; |
|
3 |
import { Observable } from 'rxjs/Observable'; |
|
4 |
import { LoadingService } from './loading.service'; |
|
5 |
import { ApiResult } from 'kl/model'; |
|
6 |
|
41fc80
|
7 |
|
W |
8 |
|
a5a648
|
9 |
@Injectable() |
W |
10 |
export class HttpClient { |
|
11 |
|
|
12 |
constructor(private http: Http, private loading: LoadingService) { } |
|
13 |
|
|
14 |
get(api: string, fun: Function) { |
|
15 |
this.getResponse(this.http.get(api), fun); |
|
16 |
} |
|
17 |
|
|
18 |
post (api: string, params: Object, fun: Function) { |
|
19 |
this.getResponse(this.http.post(api, params), fun); |
|
20 |
} |
|
21 |
|
41fc80
|
22 |
getData(id: string, fun: Function) { |
W |
23 |
return this.http.get('assets/json/data.json').map((res: Response) => res.json()).subscribe(data => { |
|
24 |
fun(data[id]); |
|
25 |
}); |
|
26 |
} |
|
27 |
|
|
28 |
|
a5a648
|
29 |
xhrPost(api, data, fun) { |
W |
30 |
let xhr = new XMLHttpRequest(); |
|
31 |
xhr.open('POST', api, false); |
|
32 |
xhr.onload = () => fun(JSON.parse(xhr.response)); |
|
33 |
xhr.setRequestHeader('Content-Type', 'application/json'); |
|
34 |
xhr.send(JSON.stringify(data) ); |
|
35 |
} |
|
36 |
|
|
37 |
private getResponse(res: Observable<Response>, fun) { |
|
38 |
res.subscribe(response => { |
|
39 |
let json = response.json(); |
|
40 |
fun(json); |
|
41 |
}, error => {} |
|
42 |
); |
|
43 |
} |
|
44 |
|
|
45 |
request<T>(url: string, method: RequestMethod, body?: any, showLoading?: boolean): Observable<ApiResult<T>> { |
|
46 |
let headers = new Headers(); |
|
47 |
|
|
48 |
let options = new RequestOptions(); |
|
49 |
options.headers = headers; |
|
50 |
options.url = url; |
|
51 |
options.method = method; |
|
52 |
options.body = body; |
|
53 |
options.withCredentials = true; |
|
54 |
|
|
55 |
let request = new Request(options); |
|
56 |
|
|
57 |
if (showLoading !== false) this.loading.show(); |
|
58 |
|
|
59 |
return this.http.request(request) |
|
60 |
.finally(() => { |
|
61 |
if (showLoading !== false) this.loading.hide(); |
|
62 |
}).map(r => r.json() as T) |
|
63 |
.catch(x => this.handleError(x)); |
|
64 |
} |
|
65 |
|
|
66 |
/** |
|
67 |
* 通用异常处理 |
|
68 |
*/ |
|
69 |
private handleError(error: Response | any) { |
|
70 |
let errMsg: string; |
|
71 |
if (error instanceof Response) { |
|
72 |
const body = error.json() || ''; |
|
73 |
const err = body.error || JSON.stringify(body); |
|
74 |
errMsg = `${error.status} - ${error.statusText || ''} ${err}`; |
|
75 |
} else { |
|
76 |
errMsg = error ? error.toString() : '服务器发生异常,请稍后再试'; |
|
77 |
} |
|
78 |
return Observable.throw(errMsg); |
|
79 |
} |
|
80 |
} |