如何创建嵌套存储管道?

时间:2019-06-11 02:39:36

标签: javascript angular rxjs

我正在尝试实现一个用例,其中有两个存储,必须从这些存储中按顺序获取值。目标是最终使用从商店中提取的这两个值来调用http服务。

我尝试创建两个SEPARATE可观察对象以分别获取值,然后将其传递给httpClient-但很好奇我是否应该这样做,还是应该像NESTED管道选择一样尝试以下操作?

function userservice() {
    this.store.pipe(
    select(fromRoot.getCategories),
    take(1),
    switchMap(category => {
        this.otherstore.pipe(
        select(fromRoot.getUsers),
        take(1),
        switchMap(user => {
           return httpClient.get( apistuff with params user and category)
        })
    })
}

我想知道这是否是正确的方法,还是应该将两个变量usercategory查找为selects(),然后调用httpclient?

1 个答案:

答案 0 :(得分:3)

从技术上讲,您的代码很好,但最好避免嵌套,因为它会导致承诺的情况-回调地狱。如果您避免嵌套,那么它会使您的代码更易于阅读/理解。

如果您的内部可观测值依赖于外部可观测值,则需要进行嵌套,否则您可以简单地组合那些可观测值以在可观测管线中发出组合值。

在您的示例中-

如果您的类别和用户是独立的,则应执行以下操作以避免嵌套-

 function userservice() {

  return combineLatest( //or you can use zip operator as per your requirement
    this.store.pipe(
      select(fromRoot.getCategories),
      take(1)),
    this.otherstore.pipe(
        select(fromRoot.getUsers),
        take(1))
  ).pipe(
    switchMap(([categories, users]) => {
        return httpClient.get( apistuff with params user and category);
    })
  );

如果用户依赖类别,则可以执行以下操作[此示例只是为了显示所需的嵌套;与您的情况无关]-

function userservice() {

  return this.store.pipe(
    select(fromRoot.getCategories),
    take(1),
    switchMap(categories => {
      return this.httpClient.get(/*get users for categories*/)
                 .pipe(
                   switchMap(users => this.httpClient.get( //apistuff with params user and category))
                 );
    })
  )  
}

通过更改如下所示的代码,可以避免嵌套在上面的代码中-

function userservice() {

  return this.store.pipe(
    select(fromRoot.getCategories),
    take(1),
    switchMap(categories => {
      return zip(this.httpClient.get(/*get users for categories*/), of(categories)); //you can use combineLatest as well as per your need
    }),
    switchMap(([users, categories]) => {
      return httpClient.get( apistuff with params user and category);
    })
  )  
}