使用Rxjs顺序订阅多个可观察对象

时间:2020-05-29 09:12:55

标签: angular rxjs

当我的表单脏了时,我试图发出一个http请求。我尝试使用zip,但无论管道结果仅适用于subscription块,它仍将发出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();
  });

2 个答案:

答案 0 :(得分:0)

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

cats.effect.Concurrent

答案 1 :(得分:0)

您可以从rxjs寻求mergeMap Operator。