Angular HttpInterceptor - 处理异步响应

Ron*_*nen 4 asynchronous indexeddb angular-http-interceptors angular

我正在编写使用 IndexedDB 缓存数据的 Angular 应用程序。

每当应用程序即将对服务器进行特定的 http 调用时,我都想从 IndexedDB 检索此数据并丰富或替换来自服务器的响应。

问题是从 IndexedDB 检索数据是返回 Observable 的异步操作,我无法将修改后的数据返回给调用服务。

拦截器看起来像这样:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  return next.handle(req).map((event) => {
    if (event instanceof HttpResponse) {
      console.log("before cacheResponseProccess");

      const val: Observable<HttpEvent<any>> = this.angularCache.cacheResponseProccess(event);

      val.subscribe(x => {
        console.log('Return modified response is:');
        console.log(x);
        return x;
      });
    }
  }).catch((error, caught) => {
    return Observable.throw(error);
  });
}
Run Code Online (Sandbox Code Playgroud)

请参阅https://stackblitz.com/edit/angular-owqgb6上的问题示例

Pen*_*gyy 5

您需要在map运算符中返回内容(在异步回调中返回值不会真正将它们返回到外部函数)。此外,当您检索异步结果以替换原始 HttpResponse 时,您可以更改mapmergeMap运算符并在其中返回一个 Observable。

尝试使用以下代码示例:

return next.handle(req).mergeMap((event) => {   // use mergeMap instead of map
  return new Observable(ob => {                 // return new Observable to retrieve asynchronous data
    if (event instanceof HttpResponse) {
      console.log("before cacheResponseProccess");

      const val: Observable<HttpEvent<any>> = this.angularCache.cacheResponseProccess(event);

      val.subscribe(x => {
        console.log('Return modified response is:', x);
        ob.next(x);         // return modified result
      });
    }
  });
}).catch((error, caught) => {
  return Observable.throw(error);
});
Run Code Online (Sandbox Code Playgroud)

固定演示