简体   繁体   中英

Angular 6 - Modifying response body in interceptor not working

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?

Just try map operator instead of tap

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM