首页 > 解决方案 > Angular/RxJS - 有一个 RxJS 管道用于流启动?

问题描述

我试图创建一种在解析某些流时动态呈现和隐藏​​加载屏幕的方法。

这是我当前的代码:

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 做到这一点的最佳方法是什么?

标签: angulartypescriptrxjsstreamreactive-programming

解决方案


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

最终,您只需this.startLoading()在开始 http 请求之前调用。

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

});

如果你真的想调用this.startLoading()管道,你可以在 http 请求开始之前调用它,从你自己的 observable 开始:

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

});

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

所以你的tap语法是正确的,它只是在你认为应该执行的时候没有执行。


推荐阅读