Angular / RxJS-是否有用于启动流的RxJS管道?

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

我试图创建一种在解析某些流时以动态方式显示和隐藏加载屏幕的方法。

这是我当前的代码:

this.requestService
        .get<Checkout>(`check/${orderNumber}`)
        .pipe(
            tap(() => this.startLoading()),  //i think this isnt the right way to use this pipe
            finalize(() => this.endLoading())
        )
        .subscribe(
            data => {
                data.orderNumber = orderNumber
                this.checkout.next(data)
            },
            error => {
                this.notification.warning(error)
            }
        )

[预期结果是我的流开始时,操作完成后当前加载屏幕显示为startLoading(),使用endLoading()隐藏加载。

我的工作代码:

this.startLoading() //basically calling function before i create the stream

this.requestService
        .get<Checkout>(`check/${orderNumber}`)
        .pipe(                
            finalize(() => this.endLoading())
        )
        .subscribe(
            data => {
                data.orderNumber = orderNumber
                this.checkout.next(data)
            },
            error => {
                this.notification.warning(error)
            }
        )

我是否正确使用此tap管道?是否有另一个管道可以更好地解决此问题?

使用RxJS做到这一点的最佳方法是什么?

angular typescript rxjs stream reactive-programming
1个回答
0
投票

在您的第一个示例中,您的点击在您的http请求完成后运行。

最终,您将只在启动http请求之前调用this.startLoading()

this.startLoading();
this.requestService.get<Checkout>(`check/${orderNumber}`).pipe(
  finalize(() => this.endLoading())
).subscribe(() => {

});

如果您really要在管道中调用this.startLoading(),则可以通过以您自己的观察对象开始,在http请求开始之前调用它:

return of(null).pipe(
  tap(() => this.startLoading()),
  concatMap(() => this.requestService.get<Checkout>(`check/${orderNumber}`)),
  finalize(() => this.endLoading())
).subscribe(() => {

});

但是这样做并没有太大意义。

所以您的tap语法是正确的,只是在您认为应该正确的时候才执行。

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