Angular 4.3 HttpClient:拦截响应

时间:2017-08-08 11:19:41

标签: javascript angular http interceptor

在关于新版Angular 4.3中包含的新HttpClientModule的文档中,非常好地解释了拦截请求的机制。还提到了响应拦截器机制,但我找不到任何关于它的信息。

是否有人知道如何拦截响应以便在将正文消息发送到服务之前对其进行修改?

感谢。

4 个答案:

答案 0 :(得分:44)

我认为您可以使用do作为@ federico-scamuzzi建议,或者您可以使用mapcatch,如下所示:

import { Injectable } from '@angular/core';
import {
  HttpErrorResponse,
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpResponse
} from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.info('req.headers =', req.headers, ';');
    return next.handle(req)
      .map((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse && ~~(event.status / 100) > 3) {
          console.info('HttpResponse::event =', event, ';');
        } else console.info('event =', event, ';');
        return event;
      })
      .catch((err: any, caught) => {
        if (err instanceof HttpErrorResponse) {
          if (err.status === 403) {
            console.info('err.error =', err.error, ';');
          }
          return Observable.throw(err);
        }
      });
  }
}
编辑:@LalitKushwah询问有关重定向if(!loggedIn)的问题。我使用Route Guards,具体来说:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot
       } from '@angular/router';

import { Observable } from 'rxjs/Observable';

import { AuthService } from '../../api/auth/auth.service';
import { AlertsService } from '../alerts/alerts.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private router: Router,
              private alertsService: AlertsService) {}

  canActivate(next: ActivatedRouteSnapshot,
              state: RouterStateSnapshot
              ): Observable<boolean> | Promise<boolean> | boolean {
    if (AuthService.loggedIn()) return true;

    const url: string = state.url;

    this.alertsService.add(`Auth required to view ${url}`);
    this.router
      .navigate(['/auth'], { queryParams: { redirectUrl: url } })
      .then(() => {});
    return false;
  }
}

然后我可以简单地将其作为我的路线的参数添加:

{
  path: 'dashboard', loadChildren:'app/dashboard/dashboard.module#DashboardModule',
  canActivate: [AuthGuard]
}

答案 1 :(得分:35)

我最近创建了一个HttpInterceptor,以解决客户端的某些JSON中的循环引用,实际上用$ref属性替换任何具有匹配{{JSON中的JSON的对象的对象1}}属性。 (如果Json.Net配置了$idPreserveReferencesHandling.Objects,则这是您获得的输出。

这里的答案对我有所帮助,但它们都没有显示如何修改响应的主体,就像OP需要的那样。为此,需要克隆事件并更新正文,如下所示:

ReferenceLoopHandling.Ignore

任何不应修改的事件都会简单地传递给下一个处理程序。

答案 2 :(得分:16)

在Angular 6版本中,他们已经适应了RxJs 6.0,因为上述大多数解决方案在此特定的angular版本中将不起作用,这是您正确修改Observable内容的方式



import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs/internal/Observable';
import {Injectable} from '@angular/core';
import {tap} from 'rxjs/operators';

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req).pipe(tap((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                event = event.clone({body: this.modifyBody(event.body)});
            }
            return event;
        }));

    }

    private modifyBody(body: any) {
        /*
        * write your logic to modify the body
        * */
    }
}


答案 3 :(得分:5)

从我能理解的内容(我只完成了对请求的拦截并注入了身份验证令牌)..你可以附加一个.do()并测试是否是一个响应......就像(如文档所说):

import 'rxjs/add/operator/do';

export class TimingInterceptor implements HttpInterceptor {
  constructor(private auth: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const started = Date.now();
    return next
      .handle(req)
      .do(event => {
        if (event instanceof HttpResponse) { //<-- HERE
          const elapsed = Date.now() - started;
          console.log(event} ms.`);
        }
      });
  }

}