Angular 4.3 HttpClient:拦截响应 [英] Angular 4.3 HttpClient : Intercept response

查看:317
本文介绍了Angular 4.3 HttpClient:拦截响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于Angular 4.3新版本中包含的新 HttpClientModule 的文档,他们很好地解释了拦截请求的机制,但是也提到了一个Response拦截器机制,但是他们从来没有说过任何关于它的信息。



这里的任何人都有想法拦截响应并在发送到服务之前修改正文消息吗?



谢谢。

解决方案

我最近做了一个 HttpInterceptor 为了解决客户端的某些JSON中的循环引用,实际上用一个 $ ref 属性替换任何对象,其中JSON中的对象具有匹配 $ id 属性。 (如果Json.Net配置了 PreserveReferencesHandling.Objects ReferenceLoopHandling.Ignore ),这是你得到的输出。 / p>

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

 拦截(req:HttpRequest< any>,next:HttpHandler):Observable< HttpEvent< any>> {
返回next.handle(req).map(event => {
if(事件实例HttpResponse&& shouldBeIntercepted(event)){
event = event.clone({ body:resolveReferences(event.body)})
}
返回事件;
});
}

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


On documentation about the new HttpClientModule included in the new version of Angular 4.3, they explain very well the mechanism to intercept request but the also mention a Response interceptor mechanism but they never say anything about it.

Anyone here has an idea to intercept response and in order to modify the body message before it is sent to the service?

Thanks.

解决方案

I recently made an HttpInterceptor in order to resolve cyclical references in some JSON on the client side, essentially replacing any object with a $ref property with the object in the JSON that has a matching $id property. (This is the output you get if Json.Net is configured with PreserveReferencesHandling.Objects and ReferenceLoopHandling.Ignore).

The answers here helped me some of way, but none of them show how to modify the body of the response, like the OP needs. In order to do so, one needs to clone the event and update the body, like so:

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

Any event that should not be modified is simply passed through to the next handler.

这篇关于Angular 4.3 HttpClient:拦截响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆