繁体   English   中英

使用 Rxjs 顺序订阅多个 observables

[英]Subscribing to multiple observables sequentially with Rxjs

当我的表单脏时,我才尝试发出 http 请求。 我尝试使用 zip 但它仍然会发出 http 请求,因为 pipe 结果仅适用于订阅块。 无论如何我不能嵌套可观察对象,因为我必须在 http 调用之后订阅另一个可观察对象,这将导致 3 个嵌套的可观察对象层。

  @ViewChild('form') 
  form: NgForm;

  // only take events when form is dirty
  const formValueChanges$ = this.form.valueChanges
    .pipe(
      debounceTime(500),
      filter(() => this.form.dirty),
      takeUntil(this._destroy$),
      distinctUntilChanged(),
      tap(result => {
        console.log(result);
      })
    );

  // http request returning an observable
  const updateForm$ = this.tempService.update();

  zip(formValueChanges$, updateForm$)
    .subscribe((response) => {
        console.log(response);
      }
    );

预期行为

this.form.valueChanges
  .pipe(
     debounceTime(500),
     filter(() => this.form.dirty),
     takeUntil(this._destroy$),
     distinctUntilChanged(),
  ).subscribe(() => {
     console.log("SAVED");
     this.tempService.update().subscribe();
  });

您可以使用concatMap运算符来确定顺序,concatMap 将等待之前的 HTTP Observable 完成,然后再从表单映射新值。

this.form.valueChanges
 .pipe(
  debounceTime(500),
  filter(() => this.form.dirty),
  takeUntil(this._destroy$),
  distinctUntilChanged(),
  concatMap(val => this.tempService.update())
).subscribe(console.log);

您可以 go 为来自 rxjs 的 mergeMap 运算符。

暂无
暂无

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

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