javascript - Angular 等待所有订阅完成

标签 javascript angular rxjs observable subscription

在 Angular 中,页面会对多个操作(例如按钮单击)进行多个 http 调用。但是,当按下最后一个“完成”按钮时,我想确保所有这些请求在进展之前都已完成。我尝试将 forkJoin 与 observables 一起使用,但它会触发请求本身,这不是我想要做的,我想要其他操作来触发请求,只是为了确保异步请求在“DONE”时完成点击。有了 promise ,我只需将 promise 推送到数组,然后执行 Promise.all(allRequests).then(()=>{})

observables: Observable<any>[];

onBtn1Click(){
   let o1 = this.service.doAction1();
   this.observables.push(o1);
   
   o1.subscribe(resp => {
        //do action1
   });
}

onBtn2Click(){
   let o2 = this.service.doAction2();
   this.observables.push(o2);
   
   o2.subscribe(resp => {
        //do action2
   });
}

onDoneClick(){
   // I would like something like this just that it wouldn't trigger the requests but make sure they are completed. 
   forkJoin(this.observables).subscribe(()=>{
     //Proceed with other things
   });
}

最佳答案

除非有人想出一种优雅的方法,否则应该采用以下方法。

我正在创建一个对象来保存来自 HTTP 请求的每个冷可观察值的热可观察值。该请求将使用 RxJS Finalize 运算符发送到其相应的热可观察对象。然后可以使用 forkJointake(1) 组合这些热可观察量,以等待源请求完成。

private httpReqs: { [key: string]: ReplaySubject<boolean> } = Object.create(null);

onBtn1Click() {
  this.httpReqs['btn1'] = new ReplaySubject<boolean>(1);
  this.service.doAction1().pipe(
    finalize(() => this.httpReqs['btn1'].next(true))
  ).subscribe(resp => {
    // do action1
  });
}

onBtn2Click() {
  this.httpReqs['btn2'] = new ReplaySubject<boolean>(1);
  this.service.doAction1().pipe(
    finalize(() => this.httpReqs['btn2'].next(true))
  ).subscribe(resp => {
    // do action2
  });
}

onDoneClick(){
  forkJoin(
    Object.values(this.httpReqs).map(repSub =>
      repSub.asObservable().pipe(
        take(1)
      )
    )
  ).subscribe(() => {
    // Proceed with other things
  });
}

关于javascript - Angular 等待所有订阅完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65627291/

相关文章:

javascript - ReactJS:是否可以在子组件中包含父组件?

javascript - map JavaScript API 自动完成 - 一个国家的城市

javascript - 每页 VS 不同的小 js 文件。 1x 站点范围的 js 文件?

Angular 编译错误 : NG6001: The class is listed in the declarations of the NgModule 'AppModule' , 但不是指令、组件或管道

angular - 如何在 Angular 6 中导入 ag-grid 主题

css - ionic 3 在 ion-content 上创建半透明覆盖层

javascript - Rx - 根据内容拆分 Observable(分组依据直到更改)

javascript - 响应式(Reactive)编程,将一组对象映射到只有一个对象字段的数组?

rxjs - 类似主题的 RxJS Observable,透明地通过 flatMap 进行管道传输

javascript - 将 Ember.js 用于仅与 Rails 一起使用的某些 View