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">
添加回答
舉報