Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 - Modifying response body in interceptor not working

Tags:

angular

I have a problem how to modify the response body with HttpInterceptor. Here is my code:

    return next.handle(modifiedReq).pipe(tap((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
            return event.clone({ body: this.modifyBody(event.body) });
        }
        return event;
    }, error => {
        this.modifyError(error);
        return of(error);
    }));

    private modifyBody(body: any) {
        //modify body here and return it
    }

The Interceptor is being called but unfortunately the event body is still the same after it's being modified. At return event; the event object has my modified body but when I jump with debugging a step forward I can see that the event is the origin one and also my services aren't working cause the expected modified body is the origin one.

I just tried to modifiy the event by changing is body like this:

event.body = this.modifyBody(event.body);

This actually works but I got an error in the angular CLI because the body-property is a constant and also in the officialy anuglar tutorials they always make clones like in my case.

So does anyone has a similiar problem or can give me any advice how to proceed here?

like image 716
Yetispapa Avatar asked Oct 24 '25 19:10

Yetispapa


1 Answers

Just try map operator instead of tap

https://www.learnrxjs.io/operators/utility/do.html tap will not modify result

like image 187
Andreq Frenkel Avatar answered Oct 26 '25 11:10

Andreq Frenkel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!