将一个可观察订阅嵌套在另一个可观察订阅中是否可以接受
Is it acceptable to nest an observable subscription within another observable subscription
我正在努力了解 Angular2 中的可观察对象。我在一个可观察的 forEach 中订阅了一个可观察的对象。
所以是这样的:
- forEach 获取路由 ID(poll id)
- (Nested in 1) subscribe 使用路由从数据库获取轮询
ID(投票 ID)
- (嵌套在 2 中)subscribe 使用从数据库中获取 createdBy 用户
轮询 ID createdById
如您所见,有很多嵌套正在进行,但感觉不对。我有更好的方法来实现这一目标吗?
这是我的代码:
poll: Poll;
createdBy: string;
constructor(public route: ActivatedRoute, public teamPollsService: TeamPollsService) { }
ngOnInit(): void {
let id: any;
// 1.
this.route.params.forEach((params: Params) => {
id = params['id'];
// 2.
this.pollService.getPoll(id).subscribe((x) => {
this.poll = x;
// 3.
this.users.getDbUser(x.createdById).subscribe((user) => {
createdBy = `${user.firstName} ${user.lastName}`;
});
});
});
谢谢。
改用flatMap()
:
this.route.params
.flatMap((params: Params) => {
id = params['id'];
return this.pollService.getPoll(id);
})
.flatMap((x) => {
this.poll = x;
return this.users.getDbUser(x.createdById);
})
.subscribe((user) => {
createdBy = `${user.firstName} ${user.lastName}`;
});
它将自动 展开 嵌套的可观察对象,这将有助于避免类似于 callback hell.
的问题
这可能不适合 Rx。
这是因为您在所有订阅中都有副作用,并且在 flatMap
或 switchMap
中执行副作用不是好的做法,因为您将无法预测它们将执行的次数当涉及其他运算符时 - 理想情况下,它们应该是纯函数。
我看到你在使用 Typescript,你应该使用 async/await
来避免所有这些回调。
我正在努力了解 Angular2 中的可观察对象。我在一个可观察的 forEach 中订阅了一个可观察的对象。
所以是这样的:
- forEach 获取路由 ID(poll id)
- (Nested in 1) subscribe 使用路由从数据库获取轮询 ID(投票 ID)
- (嵌套在 2 中)subscribe 使用从数据库中获取 createdBy 用户 轮询 ID createdById
如您所见,有很多嵌套正在进行,但感觉不对。我有更好的方法来实现这一目标吗?
这是我的代码:
poll: Poll;
createdBy: string;
constructor(public route: ActivatedRoute, public teamPollsService: TeamPollsService) { }
ngOnInit(): void {
let id: any;
// 1.
this.route.params.forEach((params: Params) => {
id = params['id'];
// 2.
this.pollService.getPoll(id).subscribe((x) => {
this.poll = x;
// 3.
this.users.getDbUser(x.createdById).subscribe((user) => {
createdBy = `${user.firstName} ${user.lastName}`;
});
});
});
谢谢。
改用flatMap()
:
this.route.params
.flatMap((params: Params) => {
id = params['id'];
return this.pollService.getPoll(id);
})
.flatMap((x) => {
this.poll = x;
return this.users.getDbUser(x.createdById);
})
.subscribe((user) => {
createdBy = `${user.firstName} ${user.lastName}`;
});
它将自动 展开 嵌套的可观察对象,这将有助于避免类似于 callback hell.
的问题这可能不适合 Rx。
这是因为您在所有订阅中都有副作用,并且在 flatMap
或 switchMap
中执行副作用不是好的做法,因为您将无法预测它们将执行的次数当涉及其他运算符时 - 理想情况下,它们应该是纯函数。
我看到你在使用 Typescript,你应该使用 async/await
来避免所有这些回调。