HttpInterceptor在拦截器内调用另一个服务并等待响应

问题描述 投票:1回答:1

如果满足某些条件,并且我希望原始服务等待新服务完成,我必须在拦截器中调用另一个服务。我的第一个解决方案是使用水龙头:

intercept(req: HttpRequest<any>, options: any, next: HttpServiceHandler)
  : Observable <HttpEvent<any>> {
    return next.handle(req, options).pipe(
      tap((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse && event.ok && event.body) {
          const productsToGet = [...]
          if (* condition *) {
            const resourceService = this.injector.get(ResourceService);
            return resourceService.getProducts(productsToGet);
          }
        }
      })
    );
  }

但是它显然不像我想要的那样工作,因为原始方法在getProducts完成之前就完成了。然后,我将这个thread中的解决方案与switchMap一起使用:

return next.handle(req, options).pipe(
  filter((event: HttpEvent<any>) => (event instanceof HttpResponse && event.ok && event.body)),
  switchMap((event: HttpResponse<any>) => {
    const productsToGet = [...]
    if (* condition *) {
      const resourceService = this.injector.get(ResourceService);
      return resourceService.getProducts(productsToGet).pipe(
        mapTo(event)
      )
    } else {
      return of(event);
    }
  })
);

但是现在我遇到了错误:

未捕获(承诺)EmptyError:顺序中没有元素。

您能告诉我我的解决方案是否有效,我应该怎么做才能使它起作用?

完整错误堆栈:

> Error: Uncaught (in promise): EmptyError: no elements in sequence
    at resolvePromise (zone.js:852)
    at resolvePromise (zone.js:809)
    at zone.js:913
    at ZoneDelegate.push.../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:26754)
    at ZoneDelegate.push.../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push.../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at drainMicroTaskQueue (zone.js:601)
    at ZoneTask.push.../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:502)
    at invokeTask (zone.js:1693)
javascript angular typescript interceptor angular-http-interceptors
1个回答
0
投票

原来这是过滤器的问题。截获的响应中的可观察值未从拦截器返回。因此,我删除了过滤器,并将其添加到switchMap内,对于不满足过滤器条件的响应,返回(event)。

© www.soinside.com 2019 - 2024. All rights reserved.