Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Sequential API calls in Angular 4

I have an array of image objects.

console.info('gallery', galleryArray);

enter image description here

The length of this array can be different. I have to make a POST request on every item of this array. The next request must be executed only after previous request has finished.

So I tried to make an array of Observable requests like this:

  let requests: Observable<Response>[] = [];
  galleryArray.forEach((image) => {
    requests.push(this._myService.uploadFilesImages(image));
  });

  console.info(requests);

enter image description here

My service looks like this:

uploadFilesImages(fileToUpload: any): Observable<any> {
  const input = new FormData();
  input.append('image', fileToUpload);
  return this.uploadHttp.post(`${this.endpoint}`, input)
  .map(
    (res: Response) => res.json()
  );
}

The question is how to perform those requests, so that every api call goes only after previous has finished? Help please. I'm new to Angular.

like image 325
Luchnik Avatar asked Aug 22 '17 10:08

Luchnik


People also ask

How do I stop multiple API calls?

How do I stop multiple API calls? On clicking on tabs you interchange state and you use ngOnInit() method every time when a state is changed to get the data.In this way, you can reduce API calls by using nested routing.

How API calls are made in angular?

We usually make API calls to remote HTTP servers via HttpClient module of Angular 10 by sending HTTP requests. HttpClient has methods which perform HTTP requests. HttpClient is an injectable class for Angular 10.


1 Answers

You are looking for the concatMap operator:

Example

const apiRoot = 'https://jsonplaceholder.typicode.com/';
const urls = [];
for (let i = 0; i < 500; i++) {
  urls.push(apiRoot + 'posts/' + (i + 1));
}
Observable.of(...urls)
  .concatMap((url: string) => this.http.get(url))
  .subscribe((result) => console.log(result));

The concatMap operator only emits after the current iterated on observable is complete. You get the results of the individual calls in the the subscribe block.

In your particular case:

 Observable.of(...galleryArray)
  .concatMap((image) => this._myService.uploadFilesImages(image))
  .subscribe((result) => console.log(result));
like image 186
EldarGranulo Avatar answered Oct 09 '22 19:10

EldarGranulo