我正在进行HTTP调用,并且想要在进行HTTP调用之前设置加载指示器。此刻我正在做:
this.loadingIndicatorService.setLoadingIndicatorOn(true)
this.cop.getunMappedTechnologyDetails().pipe(
finalize(() => {
this.loadingIndicatorService.setLoadingIndicatorOn(false);
}),
).subscribe(
res => {...}
但是我想尽可能在管道内设置loadingindicator,以确保它可以运行,并且可以轻松地将其复制/粘贴到所有订阅的前面。(我已经研究过AOP,但在这种情况下似乎不切实际)
tap不起作用,因为它先获取然后对结果起作用,但是我将其显示为可视化的内容:
this.cop.getunMappedTechnologyDetails().pipe(
tap(() => this.loadingIndicatorService.setLoadingIndicatorOn(true)),
finalize(() => {
this.loadingIndicatorService.setLoadingIndicatorOn(false);
}),
).subscribe(
res => {...}
我可能也正在研究泛型函数,但是现在我需要一个快速的解决方案,可以在订阅之前将这些管道粘贴到这些管道中。
编辑:我已经尝试过推迟使用Jan-Niklas Wortmann选项,但是在.pipe上出现错误:
然后,我尝试在管道内使用它:
this.cop.getunMappedSafeDetails().pipe(
defer(() => {
this.loadingIndicatorService.setLoadingIndicatorOn(true);
return this.cop.getunMappedSafeDetails();
}),
finalize(() => {
this.loadingIndicatorService.setLoadingIndicatorOn(false);
}),
).subscribe(...);
但是我有错误:
Argument of type 'Observable<String[]>' is not assignable to parameter of type 'OperatorFunction<String[], {}>'.
Type 'Observable<String[]>' provides no match for the signature '(source: Observable<String[]>): Observable<{}>'.
这样写:
this.cop.getunMappedTechnologyDetails().pipe(
startWithTap(() => this.loadingIndicatorService.setLoadingIndicatorOn(true)),
finalize(() => this.loadingIndicatorService.setLoadingIndicatorOn(false)),
)
每当您订阅上述Observable时,startWithTap
将立即执行您通过的所有内容,然后切换到原始Observable。最后,finalize将在源Observable完成时执行回调。
以及它的自定义运算符:
import { Observable, of } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
export function startWithTap<T>(callback: () => void) {
return (source: Observable<T>) =>
of({}).pipe(tap(callback), switchMap((o) => source));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句