angularinterception

How to modify response using Interception?


I use the following interception in Angular:

return next.handle(request).pipe(
      map((event: any) => {
        if (event.body.data) {
          return event.body.data;
        }
      }));

My JSON response contains data property. So I try to return it: return event.body.data;.

My service is:

public get(): Observable<any> {
   return this.http.get(environment.serverUrl + 'events');
}

Using service:

this.serviceEbents.get().subscribe(response => {
     console.log(response);
});

Problem is:

ERROR TypeError: Cannot read property 'data' of undefined
    at MapSubscriber.project (RequestInterception.ts:43)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next

Therefore I dont get console.log(response);.


Solution

  • The HttpClient already returns just body of the response, if you want to receive the full response, and thereby necessitate getting the body using response.body then you need to 'observe the response' described here https://angular.io/guide/http#reading-the-full-response

    your service would look like

    public get(): Observable<any> {
       return this.http.get(environment.serverUrl + 'events', { observe: 'response' });
    }
    

    otherwise just say return event

    also you should console.log the event to debug this issue.