angular - 重写嵌套订阅
问题描述
我的原始代码很难调试和维护,所以我正在重写我的代码。
原始代码
this.userService.getLocationId(id).subscribe(
(locationId) => {
this.userService.getUserParams(locationId).subscribe(
(params) => {
// This API would store users to Akita Store
this.userService.getUsers(params).subscribe()
// Get data from Akita Store
this.users$.subscribe(
(users) => {
this.users = [...users]
this.userService.putSomeUserFirst().subscribe(
(data) => {
if (data === true) {
this.users.unshift(user)
this.users = [...new Map(this.users.map(agent => [user.id, user])).values()];
}
}
)
}
)
}
)
}
)
所以基本上,我调用了几个 API,API 的参数基于之前的 API 结果,除了最后一个 API 调用。最后一个 API 调用是关于按特定顺序组织用户。
重写代码
this.userService.getLocation(id).pipe(
// Don't know which RxJS operator I should be using
flatMap((locationId) => {
if (locationId) {
return this.userService.getUserParams(locationId)
}
}),
flatMap((params) => {
return this.userService.getUser(params)
}),
flatMap(() => {
return this.users$
})
).subscribe(
(users) => {
this.users = users
}
)
我在实现原始嵌套订阅的最后一点时遇到了麻烦。重写的代码是正确的方法吗?我应该如何编写剩余部分以及我应该使用哪个 RxJS 运算符?
解决方案
是的,您采取了正确的方法。您应该始终避免嵌套subscribe
.
这将是您正在寻找的实现:
this.userService.getLocationId(id).pipe(
switchMap((locationId) => this.userService.getUserParams(locationId)),
switchMap((params) => this.userService.getUsers(params)),
switchMap(() => this.users$),
tap((users) => this.users = [...users]),
switchMap(() => this.userService.putSomeUserFirst()),
tap((data) => {
if (data === true) {
this.users.unshift(user);
this.users = [...new Map(this.users.map(agent => [user.id, user])).values()];
}
})
).subscribe();
tap
当您只想在管道内做某事时使用运算符,例如分配值。
flatMap
您在问题中使用的运算符与运算符有点不同switchMap
。在这个特定的例子中,两者都可以正常工作,但通常您将主要使用switchMap
运算符。
查看此博客以了解 RxJS 中不同的映射运算符如何工作:https ://blog.angular-university.io/rxjs-higher-order-mapping/
推荐阅读
- java - 是否所有表情符号都使用 BMP 之外的代码点构建,就像使用代理对一样?
- javascript - 如何使用 javascript 为 SVG 文本元素提供固定的高度和宽度?
- validation - 在 asp.net core razorpage 中禁用特定按钮的按钮验证
- javascript - graphqljs - 由于 graphql 错误返回错误代码 400
- paypal - Paypal Express - 隐藏运输方式和运输成本
- bash - 变量输出
- c++ - MFC C++ : IcmpSendEcho 返回成功,但状态为 IP_DEST_HOST_UNREACHABLE 且 RoundTripTime 不是默认超时时间
- python - 注释栏时无法更改宽度
- c++ - 调用 constexpr 函数的给定重载时触发编译时错误
- r - .$VariableName 的含义