【问题标题】:Matching two Observable Data Objects with combineLatest用 combineLatest 匹配两个 Observable 数据对象
【发布时间】:2018-05-16 09:10:58
【问题描述】:

我有两个可观察的数组:第一个可观察的数组对象

 array1= Observable.of({
      data: [
      {
          name: 'test',
          lastname: 'last'
        },
         {
          name: 'test1',
          lastname: 'last1'
        }
      ]
    }).map(res => {
      return res.data;
    });



// Second Observable:
    array2 = Observable.of('test1');

上述两个数组的预期结果是,只要 firstname 与 array2 值匹配,就从该对象中获取 lastname。

//Expected Result: 
object3=Observable.of('last')

【问题讨论】:

    标签: javascript typescript rxjs observable combinelatest


    【解决方案1】:

    看起来你正在使用 RxJS 5.4,所以你可以这样做,例如:

    Observable.combineLatest(array1, array2)
      .map(([users, name]) => {
        const user = users.find(u => u.name === name);
        return user ? user.lastname : null;
      })
      .subscribe(console.log);
    

    观看现场演示:https://stackblitz.com/edit/rxjs5-4nyq3s?file=index.ts

    【讨论】:

    • 谢谢马丁!快速提问 - 如果 array2 是另一个 combineLatest 的结果,这仍然可以正常工作
    • 没关系。它只需要发出至少一个项目就可以让combineLatest 发出任何东西。在实践中,这通常通过附加 startWith() 来保证
    • 不明白 startWith() 的实现
    • 例如array1.startWith(null)
    猜你喜欢
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2014-08-25
    • 2018-10-11
    相关资源
    最近更新 更多