For my application I have created the following HttpInterceptor
. Is there a way to return an altered version of the response to the request subscribers from here?
import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse, HttpErrorResponse, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
constructor(
private router: Router
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// any way to alter response that gets sent to the request subscriber?
}
}, (error: any) => {
if (error instanceof HttpErrorResponse) {
if (error.status === 401 || error.status === 403) {
console.log('The authentication session has expired or the user is not authorised. Redirecting to login page.');
this.router.navigate(['/login']);
}
}
});
}
}
Thank you.
Just like Marcel Lamothe pointed out in his answer, you can alter the response by cloning the event and changing the body property.
import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse, HttpErrorResponse, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
constructor(
private router: Router
) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// change the response body here
return event.clone({
body: 'myCustomResponse'
});
}
return event;
}).do((event: HttpEvent<any>) => {}, (error: any) => {
if (error instanceof HttpErrorResponse) {
if (error.status === 401 || error.status === 403) {
console.log('The authentication session has expired or the user is not authorised. Redirecting to login page.');
this.router.navigate(['/login']);
}
}
});
}
}
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