简体   繁体   English

使用 Rxjs 顺序订阅多个 observables

[英]Subscribing to multiple observables sequentially with Rxjs

I am trying to make a http request only when my form is dirty.当我的表单脏时,我才尝试发出 http 请求。 I tried using zip but it will still make the http request regardless as the pipe results will only apply on the subscribe block.我尝试使用 zip 但它仍然会发出 http 请求,因为 pipe 结果仅适用于订阅块。 Is there anyway for me to NOT nest the observables as I have to subscribe to another observable after the http call which will result is 3 nested layers of observable.无论如何我不能嵌套可观察对象,因为我必须在 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);
      }
    );

Intended Behaviour预期行为

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

You can use concatMap operator to be sure of the order, concatMap will wait for previous HTTP Observable to complete before mapping the new value from the form.您可以使用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);

You can go for mergeMap Operator from rxjs.您可以 go 为来自 rxjs 的 mergeMap 运算符。

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

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