结合多个条件 Observable 来准备数据

Combining multiple conditional Observables for preparing the data

我有两个 stores 需要准备组合数据

  1. 获取所有部门(前 50 个部门)
  2. 获取所有用户(例如:1000 用户)

我想合并这两个数据并准备最终数据。 注意: 该部门会要求加载所有用户(这可能需要一些时间),而且很显然,users 无法根据需要自行执行任何操作 department准备最终结果的数据。

这里是 department:

      this.store.select(getUserInfo).subscribe((info) => {
        this.store.select(getAllDepts).subscribe((depts) => {
          if (depts.length < 1) {
            this.store.dispatch(loadDeptStore({ accountId: info.acntId}));
          } else {
            console.log(depts);  // get Dept data
          }
        });
      })

对于 Users 我有的数据:

      this.store
        .select(getUserInfo)
        .pipe(
          flatMap((info) => {
            this.acntName = info.acntId;
            return this.store.select(getAllUsers, { accountId: info.acntId });
          })
        )
        .subscribe((res) => {
          if (res.length < 1 ) {
            this.store.dispatch(loadUsersInAccountStore({ billingCrmAccountId: this.acntName }));
          } else {
            console.log(res); // get users data
          }
        })

我应该使用 combineLates 还是其他东西,如果是这样,我应该如何使用 RxJS 功能以反应方式做到这一点。

首先,不要在订阅中进行订阅,它是anti-pattern。始终使用更高的可观察值。我不确切知道代码是如何工作的,因为我不使用 ngrx,但你可以像这样构建你的 observables:

    const userInfo$ = this.store.select(getUserInfo);
    userInfo$.pipe(
        mergeMap(info => {
            this.acntName = info.acntId;
            const departments$ = this.store.select(getAllDepts)
                .pipe(
                    map(depts => {
                        if (depts.length < 1) {
                            return this.store.dispatch(loadDeptStore({ accountId: info.acntId}));
                        } else {
                            return depts;  // get Dept data
                        }
                    })
                );
            const users$ = this.store.select(getAllUsers, { accountId: info.acntId })
                .pipe(
                    map(res => {
                        if (res.length < 1 ) {                          
                            return this.store.dispatch(loadUsersInAccountStore({billingCrmAccountId: this.acntName }));
                        } else {
                            return res; // get users data
                        }
                    })
                );
            return combineLatest([departments$, users$]); 
        }),
        map(([depts, users]) => {
            // do stuffs and return something
        })
    ).subscribe(res => console.log('results: ', res));
        

CombineLatest 将在您的两个可观察对象都发出一次时发出。每次其中一个 observable 发出时,它都会再次发出。
它可能不适用于您当前的实现,但您知道如何从一个来源组合两个可观察量。