【发布时间】:2019-04-01 03:35:28
【问题描述】:
我有以下包含多个订阅的代码。我需要实现的是这样的:
- 订阅激活路由以获取用户和产品数据。
- 返回商品数据后,使用商品数据订阅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;
})
});
}
});
【问题讨论】:
-
在此之前,请记住这一点。您必须在不需要时取消订阅。在这种情况下,产品创建和卖家 ID 订阅。现在你原来的问题是,你看过 rxjs 操作符吗?如果没有,请通过它们。你的问题可能会很容易被他们解决。