Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular interceptor - rxjs/map response field

Responses do not return when following interceptor is applied

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(req).pipe(
      map(response => {
        if (response instanceof HttpResponse) {
          return response.body.data;
        }
        return response;
      })
    );
  }

I would like the 'data' field of each response to be the only one present in the original caller component

Why does it happen and how can I implement this better?

I otherwise have to explicitly add pipe -> pluck('data') for each request in my project

like image 672
shuk Avatar asked Apr 18 '26 15:04

shuk


1 Answers

intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req).pipe(map((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                event = event.clone({body: event.body.data});
            }
            return event;
        }));

    }

in that function subscribe you will get response.body as data

like image 110
VENKATESH CHAVVAKULA Avatar answered Apr 20 '26 10:04

VENKATESH CHAVVAKULA



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!