在Angular 7中解析HTTP响应?

时间:2018-10-30 15:08:53

标签: angular http angular7

服务器以以下格式返回数据:{"query": 'queryName', 'result': []}

我只需要得到结果的一部分,为此我做到了:

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');

        }
    })

};

do运算符内部,我尝试了此操作:

return event.body['result'];

但是它仍然返回我整个对象。

AppModule 是:

 providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterception,
      multi: true
    },
  ],

2 个答案:

答案 0 :(得分:1)

如果要在拦截器中转换响应,则可以使用map运算符来完成。您还可以使用catchError运算符,然后在其中使用throwError,以防状态码为401

类似这样的东西:

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');
        })
      );
  }

}

这是您推荐的Sample StackBlitz

答案 1 :(得分:1)

HttpReponse的行为类似于JSON。例如,为了获取response的正文,您可以执行以下操作:

response_body = response["body"]

当然,您必须订阅。