[英]Angular : Adding the result of Http response to a map
I am sending simultaneous multiple HTTP calls from my Angular app. 我正在从Angular应用程序同时发送多个HTTP调用。 I want to save the response of HTTP calls in a Map.
我想将HTTP调用的响应保存在Map中。
data: Map<number, any> = new map<number,any>();
------------------------------------------------------
this.transactions.foreach((url)=>{
this.http.post(url,{})
.map(data => this.data.set(txnNumber, data))
})
Now since HTTP requests are sent at same time and there are chances of collision in terms of retrieval and usage of Map, it would re-write it. 现在,由于HTTP请求是同时发送的,并且在Map的检索和使用方面可能会发生冲突,因此它将重新编写它。 How can we synchronize it ?
我们如何同步呢?
You can use zip operator. 您可以使用zip运算符。 Create an Array with the request storing the transaction index, and execute with zip, when all transactions complete use a foreach to get the data of the transactions.
创建一个带有存储事务索引的请求的数组,并在所有事务完成后使用foreach来获取事务数据,并使用zip执行。
data: Map<number, any> = new map<number,any>();
------------------------------------------------------
const requests = this.transactions.foreach((url, index)=> {
return this.http.post(url,{})).map((response) => ({txNumber: index, response})
});
Observable.zip(...requests)
.map((results: any[]) => {
results.foreach((data) => this.data.set(data.txNumber, data.response))
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.