[英]Filter data from Firestore whit angularfire
我正在嘗試使用Angularfire的查詢集合從Firestore過濾數據: https : //github.com/angular/angularfire2/blob/master/docs/firestore/querying-collections.md我對此方法有些困惑。 我已經設法通過按鈕進行過濾,但是一旦完成,我不知道如何重置或刪除該過濾器。
過濾和重置所述過濾器的正確方法是什么?
在這里我有一個stackblitz: https ://stackblitz.com/edit/query-collections-in-angularfire2
到目前為止,我的代碼:
服務
filterBy() {
this.avisos = this.afs.collection('avisos', ref => ref.where('categoria','==', 'Vehículos' )).valueChanges()
return this.avisos;
};
myComponent.ts
filtrarData() {
this.avisos = this.fs.filterBy()
return this.avisos;
};
myComponent.html
<button (click)="filtrarData()" class="btn btn-outline-primary">Vehículos</button>
在您的Firebase服務中,有兩種方法,一種是獲取沒有過濾器的集合,另一種是通過給定的“類別”對集合進行過濾。
在組件中,當初始化時( ngOnInit()
函數),您從服務中調用該方法以檢索整個集合; 然后按鈕“ Vehiculos”會從您的服務中使用給定的“類別”觸發函數filtrarData()
。
過濾之后,如果您想“清理”過濾器並取回整個集合,就像按鈕調用與ngOnInit()
一樣ngOnInit()
,然后您的數組this.avisos
將再次this.avisos
整個收藏:
app.component.ts
ngOnInit() {
this.getAvisos()
}
getAvisos() {
this.avisos = this.fs.getDomiciliarios()
}
filtrarData() {
this.avisos = this.fs.filterBy()
}
然后在組件app.component.html的html中:
<button (click)="getAvisos()" class="btn btn-outline-primary btn-sm mx-1">Clean Filters</button>
<span>Filter by:</span>
<button (click)="filtrarData()" class="btn btn-outline-primary btn-sm mx-1">Vehículos</button>
<hr>
順便說一句,請注意,不需要執行return this.avisos
中的this.avisos行,這僅是服務所需要的。
另外,如果您要對firebase.service函數進行一些標准化以使收集的“ categoria”帶有一個參數,則可能會很好,以防您要為一種以上的“ categoria”類型調用它:
firebase.service.ts
filterBy(categoriaToFilter: string) {
this.avisos = this.afs.collection('avisos', ref => ref.where('categoria','==', categoriaToFilter )).valueChanges()
return this.avisos;
};
所以現在在您的app.component.html中,您可以看到類似以下內容的內容:
<button (click)="filtrarData('Vehículos')" class="btn btn-outline-primary btn-sm mx-1">Vehículos</button>
<button (click)="filtrarData('Casa')" class="btn btn-outline-primary btn-sm mx-1">Casa</button>
但請考慮到您的組件app.component.ts將包括:
filtrarData(categoriaToFilter: string) {
this.avisos = this.fs.filterBy(categoriaToFilter)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.