Angular2中的响应拦截器

Ein*_*mer 2 angular-http angular2-services angular

我将许多HTTP请求发送到服务器,并且服务器返回每个请求带有新访问令牌的响应(可能在标题或正文中).

有没有办法在它完成之前或之后处理所有响应,比如某些后端框架中的请求的中间件?

Rah*_*ngh 7

如果您使用的是Angular版本4+,您可以查看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);
        }
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

注册app.module

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

有关HttpClientModule的更多信息

如果您不使用角度v4,请在SO 链接上查看此答案