如何在一个管道中重构常见的rxjs运算符

时间:2019-11-16 08:54:55

标签: angular rxjs

我从Typeahead那里得到了Angular Powered Bootstrap的几个:

<input type="text" [ngTypeahead]="search1" />
<input type="text" [ngTypeahead]="search2" />

ts文件中:

search1 = (text$: Observable<string>) => text$.pipe(
    debounceTime(500),
    distinctUntilChanged(),
    filter((text: string) => text && text.trim().length > 0),
    switchMap((text: string) => this.service.search1(text))
);

search2 = (text$: Observable<string>) => text$.pipe(
    debounceTime(500),
    distinctUntilChanged(),
    filter((text: string) => text && text.trim().length > 0),
    switchMap((text: string) => this.service.search2(text))
);

大多数代码是相同的。它们仅在基础API中有所不同。我想重构它们,以便重复的代码可以使用。我尝试了以下操作,但不起作用:

search = (text$: Observable<string>, searchApi: (text: string) => Observable<any[]>) => text$.pipe(
    debounceTime(500),
    distinctUntilChanged(),
    filter((text: string) => text && text.trim().length > 0),
    switchMap((text: string) => searchApi(text))
);

search1 = (text$: Observable<string>) => this.search(text$, this.service.search1);

它说da未定义,其中da是服务的数据适配器。就我而言,它是HttpClient的包装。这是service的摘录:

constructor(private da: DataAdapter) {}

search1(text: string): Observable<any[]> {
    return this.da.get(...) as Observable<any[]>;
}

0 个答案:

没有答案