RxJS - 有条件地在管道中添加可观察对象

RxJS - Conditionally add observable in a pipe

所以我有如下功能

showLoader = () => <T>(source: Observable<T>) => {
  LoaderService.loadPage.next(true);
  return source.pipe(
    finalize(() => {
        LoaderService.loadPage.next(false);
    })
  );
};

然后我在进行如下 HTTP 调用时使用它

return this.http.get(url).pipe(showLoader())

但是假设我遇到这样一种情况,我需要加载程序或任何基于条件的可观察对象;类似下面

const loader : boolean = false
return this.http.get(url).pipe(concat(...), loader ? showLoader() : of(values))

我尝试使用如下所示的 iif 运算符

const loader : boolean = false
    return this.http.get(url).pipe(concat(...), mergeMap(v => iif(() => loader, showLoader(), of(v))))

并得到以下错误

TS2345: Argument of type '(source: Observable) => Observable' is not assignable to parameter of type 'SubscribableOrPromise<{}>'.

有人能帮我理解我哪里出错了以及如何纠正吗

我建议如下:

const startWithTap = (callback: () => void) =>
  <T>(source: Observable<T>) => of({}).pipe(
    startWith(callback),
    switchMap(() => source)
  );

const showLoader = () => <T>(source: Observable<T>) => concat(
  iif(
    () => loader,
    source.pipe(
      startWithTap(() => LoaderService.loadPage.next(true)),
      finalize(() => {
        LoaderService.loadPage.next(false);
      })
    ),
    EMPTY
  ), source);

return this.http.get(url).pipe(
  showLoader()
);

你可以这样做:

showLoader = (show: boolean = true) => <T>(source: Observable<T>) => {
  if (!show) { // just go straight to source
    return source;
  }

  return defer(() => { // defer makes sure you don't show the loader till actually subscribed
    LoaderService.loadPage.next(true);
    return source.pipe(
      finalize(() => {
        LoaderService.loadPage.next(false);
      })
    )
  })
};

使用:

return this.http.get(url).pipe(showLoader(false))

但是您似乎静态访问 LoaderService 的方式会在您的未来充满设计问题和错误。仅供参考。