在新版Angular 4.3中包含的关于新HttpClientModule
的文档中,拦截请求的机制得到了很好的解释.还有人提到了响应拦截机制,但我找不到任何关于它的信息.
有没有人知道如何截取响应,以便在正文消息发送到服务之前对其进行修改?
谢谢.
在新版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
* */
}
}