如何重置RxJs流

时间:2019-02-05 14:01:45

标签: angular rxjs

我具有以下自动完成的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;
   })
);

除了一件事情外,效果很好:清除搜索字段后,可观察人员不会重置。有什么好方法可以实现这一目标吗?

1 个答案:

答案 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;
    });