【问题标题】:Subscribing to multiple observables sequentially with Rxjs使用 Rxjs 顺序订阅多个 observables
【发布时间】:2020-05-29 09:12:55
【问题描述】:

我正在尝试在我的表单脏时发出 http 请求。我尝试使用 zip 但它仍然会发出 http 请求,因为管道结果仅适用于订阅块。无论如何我要嵌套可观察对象,因为我必须在 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();
  });

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    您可以使用 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);
    

    【讨论】:

      【解决方案2】:

      你可以从 rxjs 使用 mergeMap Operator。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-10
        • 2017-03-26
        • 2020-10-28
        • 2016-12-23
        • 2017-08-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多