Dar*_*ron 3 filter rxjs typescript angular2-observables
所以我有两个observable,一个返回当前类别,其他产品.我希望根据类别过滤产品.
这是在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?>)
});
Run Code Online (Sandbox Code Playgroud)
也许答案很简单,但它让我望而却步.
你需要加入这两个流,例如使用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);
});
Run Code Online (Sandbox Code Playgroud)
更新
正如@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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
900 次 |
| 最近记录: |