這篇文章給大家分享的是有關(guān)Angular http 攔截器的使用方法。小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí)。如下資料是關(guān)于Angular http 攔截器的內(nèi)容。
網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)公司!專注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、微信小程序開發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了石龍免費(fèi)建站歡迎大家使用!
Angular http的攔截器一般用來處理每個(gè)http都需要添加的參數(shù)或者是統(tǒng)一處理錯(cuò)誤信息
Angular1.x的http攔截器處理:
$httpProvider.interceptors.push(function ($q) {
return {
request: function (config) {
var url = config.url;
//這個(gè)token表示是在登錄狀態(tài), 不要用在header中,options無法設(shè)置header
if(TASApp["x-auth-token"]){
if(url.indexOf("?") == -1){
url+="?x-auth-token="+TASApp["x-auth-token"];
}else{
url+="&x-auth-token="+TASApp["x-auth-token"];
}
}
config.url = url;
return config || $q.reject(config);
},
response: function (res) {
//統(tǒng)一處理返回信息,如果是錯(cuò)誤則在這里統(tǒng)一處理,注意如果這樣處理錯(cuò)誤(reject),那么所有的錯(cuò)誤信息會(huì)進(jìn)入http的error回調(diào),在success里默認(rèn)就是成功,都可以不判斷data.success
if (res.data.success == false) {
TASApp.ajaxReturnErrorHandler(res.data["info"]); //TASApp是一個(gè)constant對(duì)象
return $q.reject(res.data); //will go to error callback
} else if (res.data.success == "relogin") {
TASApp.relogin();
return $q.reject(res.data); //will go to error callback
} else {
return res; //will go to success callback
}
},
responseError: function (res) {
//統(tǒng)一處理請(qǐng)求沒發(fā)成功的錯(cuò)誤
TASApp.ajaxErrorHandler();
return $q.reject(res);
}
};
});
Angular2.x的http攔截器處理:
export class AddHttpHeaderInterceptor implements HttpInterceptor {
constructor(private formService: FormService, private formHelper: FormHelper, private message: NzMessageService, private lang: Lang) {
}
intercept(req: HttpRequest<any>, next: HttpHandler) {
// set X-Requested-With that serve need to for ajax
let clonedReq = req.clone({headers: req.headers.set('X-Requested-With', 'XMLHttpRequest')});
if (this.formService.currentUser) {
//options http can not add x-auth-token, use param
//clonedReq = req.clone({headers: req.headers.set('x-auth-token', this.formService.currentUser['x-auth-token'])});
//global add param x-auth-token and
clonedReq = req.clone({params: req.params.set('x-auth-token', this.formService.currentUser['x-auth-token']),
headers: req.headers.set('X-Requested-With', 'XMLHttpRequest')});
}
// ===========================================================
// global handle error
// ===========================================================
return next.handle(clonedReq).pipe(
catchError(this.formService.handleError),
//handle success false
filter(res => {
if(res['statusText'] && res['statusText'] === 'OK'){
if(res['body'] && (res['body']['success'] == false || res['body']['success']=='relogin')){
if(res['body']['success'] == 'relogin'){
//handle relogin here, can add some message
(<any>window).location.href = this.formHelper.getBaseUrl()+'login';
return false;
} else {
//if no info will have a code
this.message.error(res['body']['info'] || this.lang.lang["errorCode"][res['body']['code']]);
console.log(res);
//if return false will not trigger subscribe function, if you need trigger return true
return true;
/*
this will fire subscribe error handle, that means if backend error will go to subscribe->error,
subscribe->next is only handle backend success, bug if services use like MyShares/getFormInfo that will have problem,
need add error handle for every http request and run handler function
this.http.get(url).subscribe(obj=>{handle when backend success},error=>{handle when backend error}
*/
//throw new Error("error");
}
}
}
return true;
})
);
}
}
@NgModule({
declarations: [
],
imports: [
],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: AddHttpHeaderInterceptor, deps: [FormService, FormHelper, NzMessageService, Lang], multi: true},
{provide: APP_INITIALIZER, useFactory: loginAndInitForm, deps: [FormService], multi: true},
{provide: NZ_I18N, useValue: zh_CN},
{provide: NZ_MODAL_CONFIG, useValue: {autoBodyPadding: true}},
{provide: NZ_MESSAGE_CONFIG, useValue: {nzDuration: 3000}}
],
bootstrap: [AppComponent]
})
以上就是Angular http 攔截器的使用方法介紹,詳細(xì)使用情況還得要大家自己使用過才能知道具體要領(lǐng)。如果想閱讀更多相關(guān)內(nèi)容的文章,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
文章標(biāo)題:Angularhttp攔截器的使用方法
網(wǎng)頁(yè)地址:http://bm7419.com/article10/pceddo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、品牌網(wǎng)站設(shè)計(jì)、企業(yè)建站、動(dòng)態(tài)網(wǎng)站、全網(wǎng)營(yíng)銷推廣、網(wǎng)站維護(hù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
移動(dòng)網(wǎng)站建設(shè)知識(shí)