订阅中的 Angular 订阅

sch*_*ire 9 rxjs angular

我有以下代码,其中包含多个订阅。我需要实现的是这样的:

  1. 订阅 activateRoute 以获取用户和产品数据。
  2. 返回商品数据后,使用商品数据订阅getSeller服务。
  3. 使用返回的卖家数据订阅 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;
      })

    });
  }
});
Run Code Online (Sandbox Code Playgroud)

wen*_*jun 9

从技术上讲,嵌套订阅有效,但有一种更优雅和系统的方法来处理这个问题。你真的应该更多地了解你的 RxJS 操作符。

首先,我们使用mergeMap将来自 activateRoute 的可观察值映射到内部可观察值。

然后,我们使用forkJoin将 observable 组合成单个值 observable,从而在.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

  }
Run Code Online (Sandbox Code Playgroud)

编辑:原来我误读了原来的问题,因为 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
})
Run Code Online (Sandbox Code Playgroud)