Angular 4.3 HttpClient:拦截响应

新手上路,请多包涵

在Angular 4.3新版本中关于新增 HttpClientModule 的文档中,对拦截请求的机制进行了很好的解释。还提到了响应拦截器机制,但是我找不到任何相关信息。

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

谢谢。

原文由 olivier houssin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 312
2 个回答

自 Angular 6 发布以来,RxJs 6.0 改变了它的接口,所以你不能以同样的方式使用运算符(比如 .map().tap() …)。

因此,上述大多数解决方案都已过时。

这是使用 RxJs 6.0+(使用 pipe )正确修改 Observable 内容的方法:


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

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {

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

        return next.handle(req).pipe(map((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
        * */
    }
}

原文由 imal hasaranga perera 发布,翻译遵循 CC BY-SA 4.0 许可协议

我最近制作了一个 HttpInterceptor 以解决客户端某些 JSON 中的循环引用,本质上是用 $ref 属性替换任何对象,JSON 中的对象具有匹配 $id 财产。 (如果 Json.Net 配置了 PreserveReferencesHandling.ObjectsReferenceLoopHandling.Ignore ,这是你得到的输出)。

这里的答案在某种程度上帮助了我,但没有一个显示如何修改响应的主体,就像 OP 需要的那样。为此,需要克隆事件并更新主体,如下所示:

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).map(event => {
        if (event instanceof HttpResponse && shouldBeIntercepted(event)) {
            event = event.clone({ body: resolveReferences(event.body) })
        }
        return event;
    });
}

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

原文由 sigbjornlo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题