0

I am sending simultaneous multiple HTTP calls from my Angular app. I want to save the response of HTTP calls in a 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. How can we synchronize it ?

1 Answer 1

2

You can use zip operator. 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.

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))
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.