【问题标题】:Filter observable array by object property按对象属性过滤可观察数组
【发布时间】:2019-04-06 04:02:12
【问题描述】:

我目前有一个可观察的数组,我正在使用带有异步管道的*ngFor 循环对其进行迭代。 我想通过对象上的属性值过滤 observables,例如

原始数组:

[{ name: test1,
   type: type1},
 { name: test2,
   type: type2}
 { name: test3,
   type: type1}
 { name: test4,
   type: type2}]

我想过滤这个并制作两个新的 observable(数组),一个用于 type1,一个用于 type2

我试过obs.filter(x => x.type == "type1),但它什么也没返回

然后我尝试了obs.mergeAll().filter(x => x.type == "type1"),我可以订阅它并将其正确记录到控制台,但现在它不适用于我的*ngFor(异步管道)。我猜这是因为mergeAll 意味着它不再是一个可观察的数组?那我需要把它转换回来吗?

【问题讨论】:

  • obj.type 是什么类型?字符串?
  • 是的,它是一个字符串
  • @AnjilDhamala 请不要编辑帖子以添加随机斜体和粗体降价。代码降价还可以(如果不完整),但其余部分只会使其更难阅读。

标签: angular filter rxjs observable


【解决方案1】:

您可能缺少 RXJS6 中的管道运算符。

import { of, from } from "rxjs";

import { filter, map } from "rxjs/operators";

const obs = from([{
    name: 'test1',
    type: 'type1'
},
{
    name: 'test2',
    type: 'type2'
},
{
    name: 'test3',
    type: 'type1'
},
{
    name: 'test4',
    type: 'type2'
}]);

const source = obs.pipe(
    filter(data => data.type === 'type2')
)


console.log(source.subscribe(item => console.log(item)));
// prints {name: "test2", type: "type2"}
{name: "test4", type: "type2"}

如果你想得到一个数组:


const items = [];
console.log(source.subscribe(item => items.push(item)));
console.log(items);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 2018-06-20
    相关资源
    最近更新 更多