繁体   English   中英

返回自定义Observable时,Angular HTTP客户端拦截器不起作用

[英]Angular HTTP Client Interceptor not working when returning custom Observable

仅供参考此问题与Angular Universal有关

我目前正在尝试创建一个HttpClient拦截器,该拦截器缓存GET请求并以可观察的方式返回缓存的响应。

我试图在这里角拦截器设置为指导以下https://github.com/angular/angular/blob/master/aio/content/guide/http.md ,但我似乎无法得到它的工作,当我返回除了next.handle()以外,其他可观察到的订阅都不会被触发。

这是一个矮子,演示它不起作用。 https://plnkr.co/edit/QzVpuIoj3ZFXgHm7hVW2?p=preview

拦截器示例:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  // if this is cached, return the cached response.
  return Observable.of({body: 'Test'});

  return next
    .handle(customReq)
    .do((ev: HttpEvent<any>) => {
      if (ev instanceof HttpResponse) {
        // Cache this response
      }
    });
 }

任何帮助将不胜感激。

我的最终目标是使此功能与NG Universal的传输模块一起使用。 如果我在拦截器中解决了这个问题,那么我应该已经全部准备好了。

编辑:我的假设是错误的。 Angular HttpClient Interceptor Caching示例工作得很好,对于我来说,它一定是Angular Universal。 (我用Angular的工作示例更新了Plunker,以证明它适用于这种情况)。

这是我用于Angular Universal的拦截器。

constructor(private state: TransferState) {}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (request.method !== "GET") {
        return next.handle(request);
    }

    const STATE_KEY = makeStateKey(request.urlWithParams);
    const cachedResponse = this.state.get(STATE_KEY, null);

    if (cachedResponse) {
        return Observable.of(cachedResponse);
    }

    return next.handle(request).do(event => {
        if (event instanceof HttpResponse) {
            this.state.set(STATE_KEY, event.clone());
        }
    });
}

我不确定,这可能是TransferState服务的某种计时问题。

我知道了 这是有道理的,但我不敢相信我花了这么长时间才意识到这个小问题。 当我返回Observable的cachedResponse时,我需要创建一个新的HttpResponse对象,因为它是一个类,而不仅仅是一个接口。 因此像这样:

return Observable.of(new HttpResponse<any>(cachedResponse));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM