shuk
shuk

Reputation: 1823

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

Upvotes: 3

Views: 3170

Answers (1)

VENKATESH CHAVVAKULA
VENKATESH CHAVVAKULA

Reputation: 323

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

Upvotes: 4

Related Questions