Einsamer
Einsamer

Reputation: 1087

Response Interceptor in Angular2

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?

Upvotes: 2

Views: 3776

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 19622

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

Upvotes: 7

Robert
Robert

Reputation: 3483

you can use http-interceptor Package

The package sourceng-http-interceptor

its handle every request and response of http

Upvotes: -1

Related Questions