SkinnyBetas
SkinnyBetas

Reputation: 501

How to perform an action after a subscription has completed

I'm relatively new to Angular and still trying to get my head around subscriptions. I've got a function that performs multiple http requests depending on what a user has done, i.e. delete some things, update some others. After these requests are sent and the actions completed I then want to run a 'refresh' function that's going to just be a get request to refresh the data that the user sees. But it's not waiting for the initial requests to complete before refreshing the data, is there a way that I can achieve this?

For an example it looks something like this:

private userData = [];

refresh() {
   service.getData()
      .subscribe(data => {
         this.userData.push(data);
      });
}

saveChanges() {
   this.userData.forEach(data => {
      if (data.changed) {
         service.update(data.id)
            .subscribe(res => {
               console.log(res);
            }
      } else if (data.deleted) {
         service.delete(data.id)
            .subscribe(res => {
               console.log(res);
            }
      }
   }
   
   // need this after the above has completed
   this.refresh();
}

Any help would be greatly appreciated

Upvotes: 2

Views: 1544

Answers (1)

Nikhil Patil
Nikhil Patil

Reputation: 2540

You can execute your HTTP calls in parallel using forkJoin. But I would suggest you redesign your APIs to be able to perform bulk operations.

Using forkJoin -

Observable
.forkJoin(this.userData
  .map((data) =>
  {
    if(data.changed) {
      return service.update(data.id)
    } else if (data.deleted) {
        return service.delete(data.id)  
    }
  }))
.subscribe((data) => { 
    console.log(data);
  this.refresh();
});

Upvotes: 1

Related Questions