订阅中的 Angular 订阅 [英] Angular Subscribe within Subscribe

查看:33
本文介绍了订阅中的 Angular 订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code which consists of multiple subscribes. What I need to achieve is like this :

  1. 订阅 activateRoute 以获取用户和产品数据.
  2. 返回商品数据后,使用商品数据订阅getSeller服务.
  3. 使用返回的卖家数据订阅 getRating 服务.

我的问题:有没有更好的方法来执行这些嵌套订阅?这样做是个好习惯吗?

My question : is there any better way to perform these nested subscription? is it a good practice to do like this?

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 操作符.

Technically, nesting subscribe works, but there is a more elegant and systematic way of handling this. You should really learn more about your RxJS operators.

首先,我们使用 mergeMap 来映射来自 activateRoute 的可观察值变成一个内部可观察对象.

First, we use mergeMap to map over the observable values from the activatedRoute into an inner observable.

然后,我们使用 forkJoin 将 observable 组合成单个值 observable,从而在 .subscribe()

Then, we use forkJoin to combine the observables into a single value observable, thus returning the value itself on the .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 参考.


Turns out I have misread the original question, as getRatingsByUserId is dependent on getUser. Let me make some changes. Either ways, I will leave the code above as it is, as it is good for OP's reference.

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
})

这篇关于订阅中的 Angular 订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆