Search code examples
angularangular-http-interceptorsangular7

Why does interceptor not return data to subscriber?


I use interceptor in last Angular:

return next.handle(request).pipe(
      map((event: any) => {
        if (request.method == "GET") {
          return event;
        }

        if (request.method == "POST") {
          if (event.body) {
            return event.body["result"];
          }
        }

        return event;
      }));

So, I check if it is POST request, I expect to get data from JSON with key result.

Also I tried to return data in Observer:

if (event.body) {
   return Observable.of(event.body["result"]);
}

And subscription is:

this.method.subscribe(res => {
    console.log(res);
});

Look at this pic:

console.log(event); // This is default event - first selected area 
console.log(eventToSend); /./ This is modified   - second  selected area

enter image description here

Difference is type HttpResponse, it lacks in second modified object eventToSend


Solution

  • I solved this issue using this approach:

    return next.handle(request).pipe(
          map((event: any) => {
            if (request.method == "POST") {
              if (request.body["$type"] == "LoginRequest") {
                return event;
              }
    
              if (event.body) {
                event.body = event.body["result"];
              }
            }
    
            return event;
          }),
    
          catchError((error: HttpErrorResponse) => {
            if (error.status === 401) {
              this.route.navigate(["/login"]);
            }
            return throwError(
              "Ошибка сервера RequestInterception: " + error.message || error
            );
          })
        );