【问题标题】:Add additional property to Observable array based on another array基于另一个数组向 Observable 数组添加附加属性
【发布时间】:2019-02-05 02:01:56
【问题描述】:

我有两个 Observable<MyType> 的 Observable 数组类型

export interface MyType{
  title: string;
  id: string;
  other: [];
}

如果项目存在于第二个数组中,我想将附加属性 exists 添加到第一个数组并将其设置为 true

  const combined$ = combineLatest(this.first$, this.second$);
    this.output$ = combined.pipe(
      map((x, y) => {
        return x.map(a => {
          a.title = a.title;
          a.id = a.id;
          a.other = a.other;
          a.exists = y.find(b => b.id === a.id )
        });
      })
    );

如果订阅output observable this.output$.subscribe(console.log);,总是得到[...undefined] 结果

任何想法如何解决?

【问题讨论】:

    标签: angular rxjs angular2-observables


    【解决方案1】:

    请注意find 返回在数组中找到的元素(否则未定义)。最好使用some。另外,当您返回地图上的对象时,您应该使用常规的return 语句或括号中的对象。

    const combined$ = combineLatest(this.first$, this.second$);
    this.output$ = combined.pipe(
        map(([x, y]) => {
            return x.map(a => {
                return { 
                    ...a,
                    exists: y.some(b => b.id === a.id)
                };
             });
         })
    );
    

    【讨论】:

    • 有趣的是 exists 总是 undefined 试图 debug 通过:y.some(b => { debugger; return b.id=== a.id;})debug 没有被命中,同样的事情 .find 从来没有命中调试器所以 @987654334 @总是undefined
    • 调试管道内的map,检查你从xy返回了什么。它们应该是数组,否则必须放置额外的检查。
    • 是的,现在看起来一切都很好。但是为什么你做map(([x, y]) 而不是map((x, y) 有什么区别呢?
    • combineLatest 从每个输入 Observable 返回一个包含最新值的数组。请参阅文档:rxjs-dev.firebaseapp.com/api/index/function/combineLatest
    【解决方案2】:

    在您的代码 sn-p 中,您有一个错字,您将 combineLatest rxjs 运算符的结果设置为 combined$,然后在下一行将其称为 combined,我认为这是不正确的,或者只是翻译将此问题转换为 SO 时出错。 (不管怎样,必须指出来嘿嘿)

    接下来,combineLatest 运算符返回一个包含所有可观察对象的数组。因此,您可以在 map 运算符中使用解构轻松从所有可观察对象中获取最新值。

    下面是最终代码:

    const combined$ = combineLatest(this.first$, this.second$);
    this.output$ = combined.pipe(
      map(([x, y]) => {
        return x.map(a => {
          a.title = a.title;
          a.id = a.id;
          a.other = a.other;
          a.exists = y.find(b => b.id === a.id )
        });
      })
    );
    

    在原始代码中,您实际上是将值数组作为x 传递。

    【讨论】:

      【解决方案3】:

      我认为组合发送一个值,它是一组单独的值。这里y 是未定义的。

      使用 ([x,y]) 解构 map 中的值,然后重试。 合并后的 $ 也有一个您错过的错字。 并且find 可以替换为some 以更好地表示逻辑并返回布尔值

      此外,当您使用 x.map 时,您在逻辑上映射错误的数组。

      const combined$ = combineLatest(this.first$, this.second$);
      this.output$ = combined$.pipe(
        map(([x, y]) => {
          return x.map(a => {
            a.title = a.title;
            a.id = a.id;
            a.other = a.other;
            a.exists = y.some(b => b.id === a.id )
          });
        })
      );
      

      【讨论】:

        猜你喜欢
        • 2021-11-11
        • 2022-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-21
        相关资源
        最近更新 更多