Angular2中的响应拦截器

问题描述:

我向服务器发送了很多HTTP请求,并且服务器以新的访问令牌(可能在标头或正文中)返回每个响应。Angular2中的响应拦截器

是否有任何方法可以在完成之前或之后处理所有响应,如在某些后端框架中的中间件请求?

您可以使用HTTP 拦截包装

包源ng-http-interceptor

其处理每一个请求和HTTP响应

如果您正在使用角4.0以上的版本,你可以看看HttpClientModule为拦截器提供支持。

import { Observable } from 'rxjs'; 
import {Injectable} from '@angular/core'; 
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http'; 
import { HttpErrorResponse } from "@angular/common/http"; 

@Injectable() 
export class AngularInterceptor implements HttpInterceptor { 
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    return next.handle(req).do(event => {}, err => { 
     if(err instanceof HttpErrorResponse){ 
      console.log("Error Caught By Interceptor"); 
      //Observable.throw(err); 
     } 
    }); 
    } 
} 

注册,如果你不使用的角度V4检查SO link

这个答案app.module

@NgModule({ 
    declarations: [ 
     AppComponent 
    ], 
    imports: [ 
     BrowserModule, 
     HttpClientModule 
    ], 
    providers: [ 
     [ { provide: HTTP_INTERCEPTORS, useClass: 
       AngularInterceptor, multi: true } ] 
    ], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { 
} 

更多关于HttpClientModule