2

I send many HTTP requests into a server, and the server returns each of them a response with a new access token (maybe in header or body).

Is there any way to handle all responses before or after it finishes, like middleware for a request in some back-end framework?

Einsamer
  • 1,069
  • 4
  • 17
  • 34

2 Answers2

7

If you are using Angular version 4+ you can look at HttpClientModule which provides support for interceptors.

eg

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);
        }
    });
  }
}

Register to app.module

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

More on HttpClientModule

If you are not using angular v4 check this answer on SO link

Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
-1

you can use http-interceptor Package

The package sourceng-http-interceptor

its handle every request and response of http

Robert
  • 3,373
  • 1
  • 18
  • 34