我具有以下自动完成的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;
})
);
除了一件事情外,效果很好:清除搜索字段后,可观察人员不会重置。有什么好方法可以实现这一目标吗?
答案 0 :(得分:-1)
您只需要更改运算符的顺序即可,而不是filter
内的EMPTY
内返回switchMap
(或最终例如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;
});