代码之家  ›  专栏  ›  技术社区  ›  S Panfilov

在一个对象中而不是一个数组中,是否可以将观察到的数据分组?

  •  1
  • S Panfilov  · 技术社区  · 8 年前

    我有几个 Observables ,我想做一些类似的事情 Promise.all 为了他们(也许 .forkJoin )

    const two = Observable.of(2);
    const three = Observable.of(3);
    const four = Observable.of(4);
    

    但结果是我想要一个对象而不是数组,因为我不想通过数字键访问数据。

    .subscribe(result => {  
      const two = result[0] // I don't want this
      const three = result[1]
      const four = result[2]
    })
    

    我想看到的是

     .subscribe(result => {
        const two = result.two // this is much better
        const three = result.three
        const four = result.four
      })
    

    我当然可以这样做:

    Observable
      .forkJoin(two, three, four)
      .flatMap(result  => Observable.of({two: result [0], three: result [1], four: result [2]}))
    

    但最终还是一样的——我会根据数字键获取数据。

    有什么想法吗?

    谢谢


    附笔。 一个可能的 suggested 解决方案-使用解构:

    const [two, three, four] = [...result]
    

    感觉好多了,但是如果有人改变订单 .forkJoin :

      //was
      .forkJoin(two, three, four)
      //become
      .forkJoin(two, four, three)
      // ...
      .subscribe(([two, three, four]) => {
        // say hello to "magic errors"
      })
    

    这是我的主要观点-避免这种“难找”的错误

    2 回复  |  直到 8 年前
        1
  •  3
  •   jordrake    8 年前

    我已经编写了一个实用函数,可以在 RxJS 6 . 我不知道你用的是什么版本,但希望能在那里得到支持。

    function forkJoinObj(obj) {
      const keys = Object.keys(obj);
      const values = Object.values(obj);
    
      return forkJoin(values).pipe(map(result => result.reduce((acc, next, index) => {
        acc[keys[index]] = next;
        return acc;
      }, {})));
    }
    

    请参见以下示例: https://stackblitz.com/edit/typescript-dvrff8

        2
  •  2
  •   martin    8 年前

    没有内置RxJS运算符来执行此操作,但可以使用以下语法:

    .subscribe(([two, three, four]) => {
      // ...
    })
    

    .subscribe(results => {
      const [two, three, four] = results
    }