简体   繁体   中英

Parse HTTP response in Angular 7?

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
    },
  ],

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM