import { Injectable } from '@angular/core';
|
import { Http, Headers, Response, Request, RequestMethod, RequestOptions } from '@angular/http';
|
import { Observable } from 'rxjs/Observable';
|
import { LoadingService } from './loading.service';
|
import { ApiResult } from 'kl/model';
|
|
@Injectable()
|
export class HttpClient {
|
|
constructor(private http: Http, private loading: LoadingService) { }
|
|
get(api: string, fun: Function) {
|
this.getResponse(this.http.get(api), fun);
|
}
|
|
post (api: string, params: Object, fun: Function) {
|
this.getResponse(this.http.post(api, params), fun);
|
}
|
|
xhrPost(api, data, fun) {
|
let xhr = new XMLHttpRequest();
|
xhr.open('POST', api, false);
|
xhr.onload = () => fun(JSON.parse(xhr.response));
|
xhr.setRequestHeader('Content-Type', 'application/json');
|
xhr.send(JSON.stringify(data) );
|
}
|
|
private getResponse(res: Observable<Response>, fun) {
|
res.subscribe(response => {
|
let json = response.json();
|
fun(json);
|
}, error => {}
|
);
|
}
|
|
request<T>(url: string, method: RequestMethod, body?: any, showLoading?: boolean): Observable<ApiResult<T>> {
|
let headers = new Headers();
|
|
let options = new RequestOptions();
|
options.headers = headers;
|
options.url = url;
|
options.method = method;
|
options.body = body;
|
options.withCredentials = true;
|
|
let request = new Request(options);
|
|
if (showLoading !== false) this.loading.show();
|
|
return this.http.request(request)
|
.finally(() => {
|
if (showLoading !== false) this.loading.hide();
|
}).map(r => r.json() as T)
|
.catch(x => this.handleError(x));
|
}
|
|
/**
|
* 通用异常处理
|
*/
|
private handleError(error: Response | any) {
|
let errMsg: string;
|
if (error instanceof Response) {
|
const body = error.json() || '';
|
const err = body.error || JSON.stringify(body);
|
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
|
} else {
|
errMsg = error ? error.toString() : '服务器发生异常,请稍后再试';
|
}
|
return Observable.throw(errMsg);
|
}
|
}
|