我在表单脏时尝试发出http请求only。我尝试使用zip,但无论管道结果仅适用于subscription块,它仍将发出http请求。无论如何,我是否有NOT嵌套可观察对象的方法,因为我必须在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);