我有以下由多个订阅组成的代码。我需要实现的目标是这样的:
- 订阅activatedRoute以获取用户和产品数据。
- 返回商品数据后,使用商品数据订阅getSeller服务。
- 使用返回的卖家数据订阅 getRating 服务。
我的问题:有没有更好的方法来执行这些嵌套订阅?这样做是一个好的做法吗?
this.activatedRoute.data.pipe(
map((data) => {
this.user = data['user'];
this.product = data['product'];
return this.product;
})
).subscribe(result => {
if (this.product === null) {
this.router.navigate(['/home']);
} else {
this.displayCurrency = this.dataService.getCurrencySymbolById(this.product.currency);
this.userService.getUser(this.product.createdBy).subscribe(seller => {
this.seller = seller;
this.ratingService.getRatingByUserId(seller.id).subscribe(rating => {
this.rating = rating;
})
});
}
});
从技术上讲,嵌套订阅是可行的,但有一种更优雅、更系统的方法来处理这个问题。您确实应该更多地了解 RxJS 运算符。
首先,我们使用mergeMap将 activateRoute 中的可观察值映射到内部可观察值。
然后,我们使用forkJoin将可观察量组合成单个值可观察量,从而在.subscribe()
this.activatedRoute.pipe(
tap(data => console.log(data)),
mergeMap(data => {
if (data.product === null) {
this.router.navigate(['/home']);
} else {
const getCurrency = this.dataService.getCurrencySymbolById(data.product.currency);
const getUsers= this.userService.getUser(data.product.createdBy);
const getRatings = this.ratingService.getRatingByUserId(seller.id)
return forkJoin(getCurrency, getUsers, getRatings);
}
})
).subscribe(res => {
console.log(res[0]); // currency
console.log(res[1]); // user
console.log(res[2]); // ratings
}
编辑:结果我误读了原来的问题,因为 getRatingsByUserId 依赖于 getUser。让我做一些改变。不管怎样,我都会保留上面的代码,因为它有利于OP的参考。
this.activatedRoute.data.pipe(
switchMap(data => {
this.user = data['user'];
this.product = data['product'];
return this.userService.getUser(this.product.createdBy);
}),
switchMap(data => {
if (this.product === null) {
this.router.navigate(['/home']);
} else {
this.seller = seller;
return this.userService.getRatingByUserId(this.product.createdBy);
}
})
).subscribe(res => {
console.log(res)
// handle the rest
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)