如何使用一个可观察对象的输出来过滤另一个

How to use the output of an observable to filter another

所以我有两个可观察对象,一个 returns 当前类别,另一个是其他产品。我想根据类别过滤产品。

这是在 Angular 2 中,所以我真的希望我的 ng2-view 成为订阅者(通过异步管道)。

像这个简单的例子:

let category$ = Observable.of({id: 1});
let products$ = Observable.from([{name: 'will be included', cat_ids: [1, 5]}, {name: 'nope', cat_ids: [2, 3]}, {name: 'also yep', cat_ids: [1, 7]}]);

return products$
  .toArray()
  .filter(prod => {
    return prod.cat_id.some(id => id === <how do I get the value of the category observable here?>)
  });

也许答案很简单,但它让我望而却步。

您需要加入这两个流,例如combineLatest:

let category$ = Observable.of({id: 1});
let products$ = Observable.from([{name: 'will be included', cat_ids: [1, 5]}, {name: 'nope', cat_ids: [2, 3]}, {name: 'also yep', cat_ids: [1, 7]}]);

return Observable.combineLatest(products$, category$)
  .map(([products, category]) => {
    return products.filter(prod => prod.cat_id.some(id => id === category.id);
  });

更新

正如@olsn 在 Observable.from 中指出的那样,您得到的是事件流,而不是事件数组流。因此解决方案应该是:

let category$ = Observable.of({id: 1});
let products$ = Observable.from([{name: 'will be included', cat_ids: [1, 5]}, {name: 'nope', cat_ids: [2, 3]}, {name: 'also yep', cat_ids: [1, 7]}]);

return Observable.combineLatest(products$, category$)
  .filter(([product, category]) => {
    return product.cat_id.some(id => id === category.id);
  })
  .map(([product, category]) => product);