[英]Angular 4.3 HttpClient : Intercept response
在Angular 4.3新版本中包含的新HttpClientModule
的文档中,对拦截请求的机制进行了很好的解释。 还提到了响应拦截器机制,但是我找不到任何关于它的信息。
有没有人知道如何拦截响应以便在将正文消息发送到服务之前对其进行修改?
谢谢。
我最近制作了一个HttpInterceptor
,以便在客户端解析某些 JSON 中的循环引用,实质上是将任何带有$ref
属性的对象替换为 JSON 中具有匹配$id
属性的对象。 (这是在 Json.Net 配置了PreserveReferencesHandling.Objects
和ReferenceLoopHandling.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;
});
}
任何不应修改的事件都会简单地传递给下一个处理程序。
我想你可以像@federico-scamuzzi 建议的那样使用do
,或者你可以像这样使用map
和catch
:
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]
}
自 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
* */
}
}
据我所知(我只完成了请求的拦截并注入了身份验证令牌)..你可以附加一个 .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.`);
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.