Angular&rxjs:自动完成竞争条件问题

时间:2018-10-23 08:14:58

标签: angular rxjs

我有以下代码用于从api返回数据:

private searchTerm = new Subject<string>();
public termsArray: any = [];

constructor(private apiService: DataService){
                    this.searchTerm
                    .debounceTime(200)
                    .distinctUntilChanged()
                    .subscribe(
                        term => {
                            let data = (this.apiService.getSearchTest(term))
                            if (data) {
                                data.pipe(
                                            takeUntil(this.searchTerm.pipe(skip(1)))
                                        )
                                    .subscribe(response => {
                                    this.termsArray = response.suggestions as Array<any>;
                                    console.log(this.termsArray); //just debug
                                }, err => {
                                    console.log(err);

                                });
                            }

                        });
}

autocompleteTest = (text$: Observable<string>) =>
    text$.pipe(
        debounceTime(300),
        distinctUntilChanged(),
        map(term => term.length < 1 ? []
            : this.termsArray
                .filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1)
                .slice(0, 10))
        )

onKeyUpSearch(searchText: string){
    if (searchText !== "") this.searchTerm.next(searchText);
}

因此,api调用可以正常工作,并且也可以转换为数组。 我将typeahed附加到autocompleteTest上,并且可以工作,但是具有种族条件。.经过一些研究,任何人都告诉您应该将map中的autocompleteTest函数替换为switchMap等待数据。

我该如何正确使用switchMap来避免出现竞争状况?

1 个答案:

答案 0 :(得分:0)

只需这样做:

this.searchTerm.pipe(
    debounceTime(200)
    distinctUntilChanged()
    switchMap(term => {
        let data = (this.apiService.getSearchTest(term));
        if (!data) { return of(null); }
        return data.pipe(
            takeUntil(this.searchTerm.pipe(skip(1)))
        );
    })
).subscribe(response => {
    this.termsArray = (response) ? response.suggestions as Array<any>: []; 
    console.log(this.termsArray); //just debug
}, err => {
    console.log(err);
});

我添加了一个返回of(null),因为您应该始终在switchMap运算符内部返回一个observable。否则,您将得到:

  

TypeError:您提供了“未定义”的预期流。您   可以提供Observable,Promise,Array或Iterable