[英]How to reset a RxJs stream
我有以下RxJ用於自動完成功能:
this.persons = this.searchField.valueChanges.pipe(
filter(q => q.length >= 3),
debounceTime(500),
distinctUntilChanged(),
switchMap(q => {
this.isSearching = true;
return this.service.findPerson(q).pipe(catchError(e => this.onSearchError(e)));
}),
map(res => {
this.isSearching = false;
return res.body;
})
);
除以下幾點外,該方法非常有效:清除搜索字段后,不會重置“可觀察者”。 有什么好方法可以實現這一目標嗎?
您只需要更改運算符的順序即可,而不必在switchMap
(或最終例如, of(null)
進行filter
返回EMPTY
of(null)
這取決於您要如何清除自動完成功能。
import { EMPTY } from 'rxjs';
...
this.searchField.valueChanges.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap(q => {
if (q.length >= 3) {
this.isSearching = true;
return this.service.findPerson(q).pipe(catchError(e => this.onSearchError(e)));
} else {
this.isSearching = false;
return EMPTY; // or `of(...)` with some value so you know that the autocomplete should be cleared.
}
}),
map(res => {
this.isSearching = false;
return res.body;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.