简体   繁体   English

Angular 7 - 如何使用observable链接HTTP请求

[英]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? 我设法通过用可观察量链接2个请求来使其工作,但是有更好的方法来实现吗?

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);
        });
    }
  }
 )}

You can use flatMap operator as mentioned in this answer . 您可以使用此答案中提到的flatMap运算符。

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);
      });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM