我正在使用此代码:
var rx = require('rxjs');
var fetch = require('isomorphic-fetch');
var urls = [
'http://gundam.wikia.com/api/v1/Navigation/Data'
];
var gundams = rx.Observable
.from(urls)
.flatMap(x => fetch(x))
.flatMap(x => x.json())
.map(x => x.navigation.wiki)
.filter(x => x.text === "Mobile Weapons");
gundams.subscribe(
(n) => console.log(n),
(e) => console.log(e),
(d) => console.log('done')
);
目前我没有在控制台中记录任何结果(“完成”除外)。
如果我删除可观察对象上的最后一条链 (.filter(x => x.text === "Mobile Weapons");
) 并更改
(n) => console.log(n),
到
(n) => console.log(n.filter(x => x.text === "移动武器")),
我将预期结果记录到控制台
[ { text: '移动武器',
href: '/wiki/Special:RunQuery/Weapon_query',
子级: [ [对象], [对象], [对象], [对象] ] } ]
我可能只是误解了可观察量的工作原理,但我很好奇如何更改我的代码,以便不必在订阅回调中使用过滤器。
最佳答案
这是因为 map
返回对象数组,因此您的过滤函数接收的是该数组,而不是您尝试过滤的数组内容。
这与您在订阅中执行过滤器时起作用的原因相同。由于 map 返回对象数组,您可以过滤该数组并且它按预期工作。
您需要使用flatMap
,以便过滤器接收数组中的项目而不是数组。
var urls = [
'http://output.jsbin.com/qimutofedi.json'
];
var gundams = Rx.Observable
.from(urls)
.flatMap(x => fetch(x))
.flatMap(x => x.json())
.flatMap(x => x.navigation.wiki) // <--- flatten out the array to emit its values
.filter(x => x.text === "Mobile Weapons");
gundams.subscribe(
(n) => console.log(n),
(e) => console.log(e),
(d) => console.log('done')
);
上面将记录:
Object {text: "Mobile Weapons", href: "/wiki/Special:RunQuery/Weapon_query",children: Array[4]}
children:Array[4]
href:"/wiki/Special:RunQuery/Weapon_query"
text:"Mobile Weapons"
__proto__:Object
关于javascript - 为什么过滤 observable 订阅的结果会得到与过滤 observable 本身不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37876954/