0
votes

I am trying to make a http request only when my form is dirty. I tried using zip but it will still make the http request regardless as the pipe results will only apply on the subscribe block. 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.

  @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();
  });
2

2 Answers

0
votes

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.

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

You can go for mergeMap Operator from rxjs.