1 回答
TA贡献1784条经验 获得超2个赞
您不会将 observable 全部返回到async管道中。您正在执行手动订阅并映射结果。
filterFunction() {
this.countries = this.filter.valueChanges.pipe(
startWith(''),
switchMap(text => this.search(text))
);
}
search(text: string): Observable<any[]> {
return this.sampleFunction().pipe(
map(countries => {
return countries.filter(country => {
const term = text.toLowerCase();
return country.caseID.toLowerCase().includes(term)
|| (country.word).toLowerCase().includes(term)
|| (country.product).toLowerCase().includes(term);
});
});
);
}
sampleFunction(): Observable<any[]> {
return this.extractorService.dbFirestore().pipe(
map(data => data.map(x => x.payload.doc.data()))
);
}
我建议尽可能向函数添加返回类型,Typescript 非常擅长发现像这样的基于类型的小错误。
现在的一个潜在问题是this.extractorService.dbFirestore()每次过滤器值更改时都会调用它。如果你不希望这种情况发生,你需要一种不同的方法。
处理静态数据
您可能只想先加载数据,然后过滤固定数组。在这种情况下,您将首先加载数据,然后将值更改与concatMap.
filteredCountries$: Observable<any[]>;
private countries: any[];
filterFunction() {
// load the countries first
this.filteredCountries$ = this.getCountries().pipe(
// set the countries
tap(countries => this.countries = countries),
// now start observing the filter changes
concatMap(countries => {
return this.filter.valueChanges.pipe(
startWith(''),
map(text => this.search(text))
})
);
}
search(text: string): any[] {
return countries.filter(country => {
const term = text.toLowerCase();
return country.caseID.toLowerCase().includes(term)
|| (country.word).toLowerCase().includes(term)
|| (country.product).toLowerCase().includes(term);
});
}
getCountries(): Observable<any[]> {
return this.extractorService.dbFirestore().pipe(
map(data => data.map(x => x.payload.doc.data()))
);
}
然后您的 HTML 将被观看filteredCountries$而不是countries.
<tr *ngFor="let item of filteredCountries$ | async">
添加回答
举报