angular拦截器拦截ajax,Angular http 拦截器

Angular http的拦截器一般用来处理每个http都需要添加的参数或者是统一处理错误信息

Angular1.x的http拦截器处理:

$httpProvider.interceptors.push(function ($q) {

return {

request: function (config) {

var url = config.url;

//这个token表示是在登录状态, 不要用在header中,options无法设置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) {

//统一处理返回信息,如果是错误则在这里统一处理,注意如果这样处理错误(reject),那么所有的错误信息会进入http的error回调,在success里默认就是成功,都可以不判断data.success

if (res.data.success == false) {

TASApp.ajaxReturnErrorHandler(res.data["info"]); //TASApp是一个constant对象

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) {

//统一处理请求没发成功的错误

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, 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

(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]

})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值