Angular 4.3 HttpClient : Intercept response

后端 未结 4 1221
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 12:59

In the documentation about the new HttpClientModule included in the new version of Angular 4.3, the mechanism to intercept requests is explained very well. Ther

4条回答
  •  情书的邮戳
    2020-12-02 13:31

    Since Angular 6 release, RxJs 6.0 changed its interface, so you cannot use operators the same way (like .map(), .tap()...).
    Because of that, most of the above solutions are outdated.
    This is how you correctly modify content of an Observable using RxJs 6.0+ (with pipe):

    
    import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
    import {Injectable} from '@angular/core';
    import {Observable} from 'rxjs';
    import {map} from 'rxjs/operators';
    
    @Injectable()
    export class ResponseInterceptor implements HttpInterceptor {
    
        intercept(req: HttpRequest, next: HttpHandler): Observable> {
    
            return next.handle(req).pipe(map((event: HttpEvent) => {
                if (event instanceof HttpResponse) {
                    event = event.clone({body: this.modifyBody(event.body)});
                }
                return event;
            }));
    
        }
    
        private modifyBody(body: any) {
            /*
            * write your logic to modify the body
            * */
        }
    }
    
    

提交回复
热议问题