Sa Hagin
Sa Hagin

Reputation: 532

Angular 7 - How to chain HTTP request with observables

I want to be able to remove an alert, but only if this alert is not assigned to an user. For that I need to get my users list and check if no user has this alert assigned. I managed to make it work by chaining 2 requests with observables, but is there a better way to achieve that?

deleteAlert(id: number) {
  this.usersService.getUsers().subscribe(
    (users) => {
      if (users.filter((value) => value.alert.id === id).length > 0) {
        console.log('Deassing alert to all user first');
      } else {
       this.alertService.deleteVillain(id)
        .subscribe(() => {
          this.alertsList =this.alertsList.filter(alerts=>alerts.id!==id);
        });
    }
  }
 )}

Upvotes: 2

Views: 3239

Answers (1)

Koushik Ravulapelli
Koushik Ravulapelli

Reputation: 1138

You can use flatMap operator as mentioned in this answer.

deleteAlert(id: number) {
      this.usersService.getUsers().flatMap(
        (users) => {
          if (users.filter((value) => value.alert.id === id).length > 0) {
            console.log('Deassing alert to all user first');
          } else {
           return this.alertService.deleteVillain(id);
        }
      }).subscribe(data=>{
         this.alertsList = this.villainsList.filter(alerts=>alerts.id!==id);
      });
}

Upvotes: 1

Related Questions