1

As per my requirement, I need to send async request using the Angular 6 Httpclient.
Can anyone explain howe can send async request?

Loop calling in Component:

function in REST API service:

Right now, all request is going all together. But I want that after complete first request request 2nd should go and so all.

Please let me know is this possible in Angular 6?

Please try to provide me some good example.

this.pressArray.forEach(function(field_value, field_index){
  restAPI.CallAddPageBlock(formData, '', id).subscribe(response2 => {
    content_blocks.push(response2.id);
  });
});


CallAddPageBlock(formData, tickets='', id): Observable<any> {
  var full_url = this.baseUrlContent + 'Hub_PageBlock_C/assets/';
  if(id!=0){
    full_url = full_url+id
  }
  return this.http.post(full_url, formData, this.httpOptionsJson).pipe(); 
}
Sophie
  • 2,000
  • 1
  • 12
  • 15
Amit Vijay
  • 11
  • 2
  • It is possible, more info https://angular.io/guide/http#making-a-post-request – Alexander Dec 06 '18 at 13:00
  • Is there a class that is being assigned this work or is this a pure coincidence? I just answered a very similar question an hour or 3 ago: [Execute http request sequentially in Angular 6](https://stackoverflow.com/q/53654176/1260204) – Igor Dec 06 '18 at 17:09

1 Answers1

2

You could use async/await with Promise to stream line this. Convert the observable to a promise using toPromise()

async doSomethingAsync() {
  for(var item of this.pressArray) {
    let response2 = await restAPI.CallAddPageBlock(formData, '', id).toPromise();
    content_blocks.push(response2.id);
  }
}

There is no need to call pipe in CallAddPageBlock at the end there.

For more on async/await see also this excellent answer and scroll to the heading ES2017+: Promises with async/await.

Igor
  • 60,821
  • 10
  • 100
  • 175