angular - 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 做到这一点的最佳方法是什么?
解决方案
在您的第一个示例中,您的点击在您的 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
语法是正确的,它只是在你认为应该执行的时候没有执行。
推荐阅读
- python - 在python中解析列表的子列表
- c++ - cmake 错误 [SDK/Util/CMakeLists.txt:132 (add_library) 处的 CMake 错误]
- apache-kafka - Spring Cloud Stream Binding Consumer 属性不起作用
- sql - SparkSQL - 两个时间戳之间的差异(以分钟为单位)
- android - Discord OAuth2登录失败通过Android Webview
- javascript - 使用 Sequelize 在 GraphQL 查询中将日期时间字段作为字符串输出
- javascript - 如何将 JSON 转换为 Javascript 数组?
- xpath - xpath 在某个元素之后或元素之间选择文本
- r - 我可以创建一个带有文本输入的 R 函数以进行绘图吗
- reactjs - 如何将文件从反应保存到天蓝色文件存储?