[英]Return an array/object instead of an observable using RXJS map
我有以下代码,它返回一个带有每个项键的项详细信息的observable:
this.list = this.af.database.list("API_URL")
.map((ItemKeys) => {
return ItemKeys.map((ItemKey) => {
return this.af.database.object(API_URL + "/" + ItemKey); //I need this as the object (not observable)
});
}).subscribe((items) => {
this.lineData = items; //A list of observables
});
代码迭代每个项密钥并从另一个端点获取项数据。 问题是它重新编译每个项目数据的可观察量,我需要它在一个对象(可观察的结果)中。
我尝试使用以下代码返回订阅结果,但随后我的所有项目数据都为空(未定义):
this.list = this.af.database.list("API_URL")
.map((ItemKeys) => {
return orderItemKeys.map((ItemKey) => {
this.af.database.object("API_URL" + "/ItemKey.$key) // So I tried to subscribe to this..
.subscribe((data) => {
return data;
});
});
}).subscribe((items) => {
this.lineData = items; // A list with undefined items
});
如何将项数据对象作为对象返回,而不是在我的情况下作为对象的可观察对象?
不要在运营商内返回订阅(来自订阅)。 那可能不是你想打算做的。
对于检索对象列表的内部部分,您应该能够将从Array#map()
创建的可观察Array#map()
转换为具有Observable#from()
的高阶observable。 您需要mergeAll()
将这一系列的observable恢复为单个流,然后使用toArray()
将所有发出的项收集到一个数组中。 然后使用mergeMap()
提取最后一个observable。
this.list = this.af.database.list("API_URL")
.mergeMap((ItemKeys) => {
return Observable.from(ItemKeys.map((ItemKey) => {
return this.af.database.object(API_URL + "/" + ItemKey);
})).mergeAll().toArray();
})
.subscribe((items) => {
this.lineData = items;
});
你应该用flatMap
替换map
,因为它能够展平Observable<Observable<T>>
。
var responseStream = requestStream
.flatMap(function(requestUrl) {
return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
});
responseStream.subscribe(() => {});
尝试调整和简化您的代码
const databaseList = () => Rx.Observable.from(['a6b54x4', '1e23sa4q']);
const databaseObject = (id) => Rx.Observable.of({ id, status: 'ok' })
databaseList()
.flatMap(x => databaseObject(`id/${x}`))
.reduce((x, y) => x.concat(y), [])
.subscribe(console.log);
基本上,它仍然使Observable<Observable<T>>
变平,然后使用reduction,将所有内容合并到一个结果数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.