在新版Angular 4.3中包含的关于新HttpClientModule的文档中,拦截请求的机制得到了很好的解释.还有人提到了响应拦截机制,但我找不到任何关于它的信息.

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

谢谢.

推荐答案

Since Angular 6 release, RxJs 6.0 changed its interface, so you cannot use operators the same way (like .map(), .tap()...).
Because of that, most of the above solutions are outdated.
This is how you correctly modify content of an Observable using RxJs 6.0+ (with pipe):


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
        * */
    }
}

Angular相关问答推荐

在forkjoin中使用NGXS状态数据

为什么在回调完成之前,可观察对象会返回?

当嵌套在异步容器中时,S会阻止具有动态值的ionic 段工作吗?

将sass与@Use语句一起使用时出现Angular 新的VITE构建器编译错误

懒惰加载角404路径

ANGLE v16独立组件不能与拦截器一起工作?

Angular 15 在 URL 中使用@进行路由

ngRouterOutlet和组件生命周期使用自定义模板渲染的问题

从 Angular 应用程序中删除散列标签后无法从 Apache 访问 API

为什么 Angular2 (click) 事件没有在

ViewChild 和 ContentChild 的所有有效 Select 器是什么?

Angular 4.3拦截器不起作用

在Angular 4中以'yyyy-MM-dd'格式获取当前日期

在 Angular 中动态设置样式

将 Angular 5 升级到 6 时,我得到不兼容的对等依赖(使用 ng update @angular/core)

在Angular 6 中找不到 HammerJS

错误:angular2 中没有 HttpHandler 的提供者

Angular 5 和material - 如何从 SnackBar 组件更改背景 colored颜色

如何作为模块的子模块路由到模块 - Angular 2 RC 5

在 Angular 2 中对 observable 进行单元测试