Reputation: 12015
Server returns data in this format: {"query": 'queryName', 'result': []}
.
I need to get only result part, for that I did this:
export class RequestInterception implements HttpInterceptor {
public constructor(private route: Router) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
return event.body['result'];
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
this.route.navigate(['/login']);
}
return throwError('backend comm error');
}
})
};
Inside do
operator I tried this:
return event.body['result'];
But it still returns me whole object instead.
AppModule is:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: RequestInterception,
multi: true
},
],
Upvotes: 2
Views: 6249
Reputation: 922
An HttpReponse
behaves like a JSON. For example, in order to get the body of your response
you can do the following:
response_body = response["body"]
Of course, you have to subscribe.
Upvotes: 1
Reputation: 39432
If you want to transform the response in the interceptor, then you can do it with a map
operator. You can also use the catchError
operator and then inside that, use throwError
in case the status code is 401
.
Something like this:
import { Injectable } from '@angular/core';
import {
HttpInterceptor, HttpRequest, HttpResponse,
HttpHandler, HttpEvent, HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
@Injectable()
export class InterceptorService implements HttpInterceptor {
constructor(private route: Router) { }
intercept(
req: HttpRequest<any>,
next: HttpHandler
) {
return next.handle(modified)
.pipe(
map((event: HttpResponse<any>) => {
event['body'] = event.body['result'];
return event;
}),
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
this.route.navigate(['/login']);
}
return throwError('backend comm error');
})
);
}
}
Here's a Sample StackBlitz for your ref.
Upvotes: 1