2

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);
        });
    }
  }
 )}
Sa Hagin
  • 502
  • 1
  • 7
  • 18
  • 1
    Possible duplicate of [Chaining RxJS Observables from http data in Angular2 with TypeScript](https://stackoverflow.com/questions/35268482/chaining-rxjs-observables-from-http-data-in-angular2-with-typescript) – Koushik Ravulapelli May 17 '19 at 14:58
  • Wouldn't it make more sense to create a state var that indicated assigment status for each alert? Then it becomes a simple Boolean test. Psuedo code: `this.alertService.isNotAssigned(id) then delete it` – Randy Casburn May 17 '19 at 14:58

1 Answers1

1

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);
      });
}
Koushik Ravulapelli
  • 1,140
  • 11
  • 30