我从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[]>;
}