如何在 angular 中从复杂方法返回 ArrayList()



我的问题很简单。考虑以下角度方法:

getAllOrdersHeaders(){
this.getAllOrdersIds().subscribe(idList=>{
idList.forEach(id=>{
this.ordersCollection.doc(id).collection('metadata').doc('metadata').get()
.subscribe(metadata=>{
console.log(metadata.data());
});
})
});
}

前面的方法,浏览Firebase文档的ID列表,以查找文档的元信息。

问题是:如何返回这些元数据对象的列表,而不是在控制台上打印它们?

简而言之:您无法以同步方式返回这些对象。您只能通过自己返回可观察对象的承诺来异步返回它们。

您可以使用回调

let array = [] // global variable
// declaring callback function outside
addMetaData = (val) => {
array.push(val);
}
// Now use getAllorders function
getAllOrdersHeaders(callbackFunction){
this.getAllOrdersIds().subscribe(idList=>{
idList.forEach(id=>{
this.ordersCollection.doc(id).collection('metadata').doc('metadata').get()
.subscribe(metadata=>{
callbackFunction(metadata.data()); // whenever the data is fetched you are calling the function to store data
});
})
});
} 
// Now call getAllOrders with callbackFunction ie addMetaData
getAllOrders(addMetaData);
// the result will be stored in the array variable declared on the top

最新更新