[英]Subscribing to multiple observables sequentially with Rxjs
僅當我的表單臟時,我才嘗試發出 http 請求。 我嘗試使用 zip 但它仍然會發出 http 請求,因為 pipe 結果僅適用於訂閱塊。 無論如何我不能嵌套可觀察對象,因為我必須在 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);
您可以 go 為來自 rxjs 的 mergeMap 運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.