[英]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:“(來源:Observable)=> Observable”類型的參數不可分配給“SubscribableOrPromise<{}>”類型的參數。
有人能幫我理解我哪里出錯了以及如何糾正它
你可以這樣做:
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
的方式在您的未來充滿了設計問題和錯誤。 供參考。
我建議如下:
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()
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.