简体   繁体   English

在Angular 7中解析HTTP响应?

[英]Parse HTTP response in Angular 7?

Server returns data in this format: {"query": 'queryName', 'result': []} . 服务器以以下格式返回数据: {"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: do员里面do我试过了:

return event.body['result'];

But it still returns me whole object instead. 但是它仍然返回我整个对象。

AppModule is: AppModule是:

 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. 如果要在拦截器中转换响应,则可以使用map运算符进行响应。 You can also use the catchError operator and then inside that, use throwError in case the status code is 401 . 您还可以使用catchError运算符,然后在其中使用throwError ,以防状态码为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. 这是供您参考的示例StackBlitz

An HttpReponse behaves like a JSON. HttpReponse行为类似于JSON。 For example, in order to get the body of your response you can do the following: 例如,为了获得response的主体,您可以执行以下操作:

response_body = response["body"]

Of course, you have to subscribe. 当然,您必须订阅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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