Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept the response in angular 4 with HttpInterceptor

I do have the following Interceptor:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(private tokenService: TokenService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.tokenService.getToken();

    if (token) {
      const authReq = req.clone({
        headers: req.headers.set('Authorization', `Bearer ${token}`)
      });

      return next.handle(authReq);
    }

    return next
      .handle(req)
//
      .getSomehowTheResponse()
      .andSaveTheTokenInStorage()
      .andPropagateNextTheResponse()
  }
}

And I want to save the token from the response header in local storage, all the tutorials are showing how to intercept the request, but not very clearly the response.

like image 263
Alexandru Olaru Avatar asked Sep 12 '17 05:09

Alexandru Olaru


People also ask

How do you intercept HTTP response?

To intercept HTTP requests, use the webRequest API. This API enables you to add listeners for various stages of making an HTTP request. In the listeners, you can: Get access to request headers and bodies and response headers.

How do I use HttpInterceptor?

To use the same instance of HttpInterceptors for the entire app, just import the HttpClientModule into your AppModule, and add the interceptor to the root application injector. Suppose you import HttpClientModule multiple times in different modules (for example, in a lazy-loading module).

What is intercept in angular?

This communication is based on two significant concepts: authorization and authentication. Interceptors are another significant part of Angular programming. They are used to modify the HTTP requests by adding several functionalities. Authentication determines the security level of an application.

Can angular have multiple HTTP interceptors?

After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.


1 Answers

you also need to import library

    import 'rxjs/add/operator/map';

then you use as below. you also need to return the event object so that it can be received in your subscribe() function.

    return next.handle(req).map((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response and headers you want
      }
      return event; 
    });
like image 50
Atif Hussain Avatar answered Oct 08 '22 18:10

Atif Hussain