Search code examples
angularangular4-httpclient

Multiple data post to server in Angular 4


I'm building some application that need to be able to run offline, so when it's offline i cache every data post in localstorage, and when the browser detect that it's online, i read that cache and begin pushing all data to the server using HttpClient.

The problem is this push all data asynchronously, making it not always pushing in order of data 0 to N, i wonder if there's some algorithm that wait for the first push to end before continuing to the second push? i don't want to use setTimeout as this is slow, i want to keep it speedy while making it run in order.


Solution

  • I think forkJoin is the good solution you can use here.

    You can add all the requests in an array like following

    constant allSavedRequests = [];
    
    allSavedRequests.push(this.http.get('https://testdb1.firebaseio.com/.json'));
    allSavedRequests.push(this.http.get('https://testdb2.firebaseio.com/.json'));
    

    Now using forkJoin you can bind all requests in one variable

    const runRequests = Observable.forkJoin(allSavedRequests)
    

    Finally when you are online you need to invoke forkJoin call and it will make all the requests in one shot.

    runRequests.subscribe(latestValues => {
      console.log( "data_all" , latestValues);
    });
    

    Read More about forkJoin.