我正在努力处理一个简单的RxJs查询,我似乎无法解决这个问题。我似乎无法弄清楚如果将Observable包装在一个对象中,如何合并它们。如果我只是直接从flatMap返回Observable,这个例子按预期工作,但我也需要输出中的名字。我怎样才能做到这一点?
我正在使用RxJS 5.0.0-beta.2
基本数据结构:
var data = [
{
"name": "Test #1",
"users": [
{
"name": "John Doe",
"gender": "male"
},
{
"name": "John Doe",
"gender": "male"
},
{
"name": "Jane Doe",
"gender": "female"
}
]
},
{
"name": "Test #2",
"users": [
{
"name": "John Doe",
"gender": "male"
},
{
"name": "Jane Doe",
"gender": "female"
},
{
"name": "Jane Doe",
"gender": "female"
}
]
}
];
RxJs功能:
Observable.fromArray(data)
.flatMap(x => {
return Observable.of({
"name": x.name,
"count": Observable.fromArray(x.users)
.filter(x => x.gender == "male")
.count()
})
})
.toArray()
.subscribe(result => {
console.log(result);
});
期望的结果:
result = [
{
"name": "Test #1",
"count": 2
},
{
"name": "Test #2",
"count": 1
}
];
实际结果:
result = [
{
"name": "Test #1",
"count": Observable
},
{
"name": "Test #2",
"count": Observable
}
];
答案 0 :(得分:1)
Observable.fromArray(data)
.flatMap(x => {
return Observable.of({
"name": x.name,
"count": x.users
.filter(x => x.gender == "male")
.length
});
})
.toArray()
.subscribe(result => {
console.log(result);
});