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.
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.
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).
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.
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.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With