
最近在項(xiàng)目中折騰了下angular2,所以出來跟大家分享,希望有幫助,每個公司業(yè)務(wù)不一樣,按實(shí)際情況而定
(1).導(dǎo)入依賴
/**
* name:http服務(wù)
* describe:對http請求做統(tǒng)一處理
* author:1490040004@qq.com
* date:2017/5/15
* time:09:29
*/
import {Injectable} ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?from '@angular/core';
import {Http, Response, Headers, RequestOptions, Request} ? ? ? ? ?from '@angular/http';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class HttpInterceptorService {
constructor(private http: Http) {
}
(2).發(fā)送請求統(tǒng)一處理
//發(fā)送請求統(tǒng)一處理
public request(params: any): any {
let options = new RequestOptions({
method: (params['method'] == 'post' || params['method'] == 'POST') ? 'POST' : 'GET',
url: params['url'],
headers: new Headers({'content-type': 'application/json', 'Accept': 'application/hal+json;charset=UTF-8'}),
params: !(params['method'] == 'post' || params['method'] == 'POST') ? params["data"] : {},
body: (params['method'] == 'post' || params['method'] == 'POST') ? JSON.stringify(params["data"]) : {}
});
return this.http.request(new Request(options))
.toPromise()
.then(this.handleSuccess)
.catch(res=>this.handleError(res));
}
(3).處理請求成功
private handleSuccess(res: Response) {
let body = res["_body"];
if (body) {
? ?return {
? ?data: res.json().content || {},
? ?page: res.json().page || {},
? ?statusText: res.statusText,
? ?status: res.status,
? ?success: true
? }
}
else {
? ?return {
? ?statusText: res.statusText,
? ?status: res.status,
? ?success: true
? ?}
?}
}
(4).處理錯誤
private handleError(error) {
console.log(error);
let msg = '請求失敗';
if (error.status == 400) {
? ?console.log('請求參數(shù)正確');
?}
if (error.status == 404) {
? ?console.error('請檢查路徑是否正確');
?}
if (error.status == 500) {
? ?console.error('請求的服務(wù)器錯誤);
?}
console.log(error);
return {success: false, msg: msg};
? }
}
<完>
福利:如果你是喜歡看書的朋友,不妨點(diǎn)擊【有驚喜】這是我在亞馬遜買的電子書。都非常珍貴,希望你能喜歡
作者:小處成就大事
簡介:一個喜歡分享和學(xué)習(xí)的前端開發(fā)程序猿,平時喜歡看看書,游泳,爬山,戶外騎行等,期待與志同道合的你成為朋友,一起交流、一起進(jìn)步。
初衷:對我來說,寫文章是學(xué)習(xí)和記錄一些沒有精通和完全掌握的知識點(diǎn),其次才是分享知識。通過自己查找資料和經(jīng)驗(yàn)心得整理出來,做到通俗易懂分享給需要的人,分享知識不是為了炫耀,也不是為了謀利,而是為了更多需要汲取知識的人,可以收獲知識,同時自己也可以從中收獲知識,堅(jiān)持做知識分享真的很難,但是我會堅(jiān)持下去····
博客:小處成就大事_新浪博客
如果有志同道合的朋友不妨加微信一起交流和學(xué)習(xí),期待你的到來
