我有以下代码,它返回一个包含每个项目键的项目详细信息的可观察对象:
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()
创建的可观察对象数组转换为使用 的高阶可观察对象可观察#from()
。您需要 mergeAll()
将这一系列的 observable 返回到单个流,然后使用 toArray()
将所有发出的项目收集到一个数组中。然后使用 mergeMap()
提取最后一个可观察值。
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;
});
关于angular - 使用 RXJS 映射返回数组/对象而不是可观察对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40917376/