Due to the limitation of firebase realtime database to filter on multiple fields i am trying to filter the data on client side. I have declared a variable which matches with a field in the result set. But i am unable to refresh the results while changing the field. I know there is something wrong with the way i am filtering the data. Could someone please someone show some paths to achieve this.
Typescript:
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/compat/database';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Item } from '../models/item';
@Component({
selector: 'test-component',
templateUrl: './test-component.html',
styleUrls: ['./test-component.scss']
})
export TestComponent implements OnInit {
itemRef: Observable <Item[]> = new Observable();
group_id: number = 5; //dynamic
currentTypeSelected: number = 2; //dynamic
currentTypeBehaviorSubject: BehaviorSubject<number> = new BehaviorSubject<number>(2);
constructor(
private _db: AngularFireDatabase,
){ }
ngOnInit(): void {
this.itemRef = this._db.list('/items', ref => ref.orderByChild('group_id').equalTo(this.group_id)).snapshotChanges().pipe(
map(action => action.map(a => {
const obj = a.payload.val();
return new Item(obj);
}).filter(item => item.type == this.currentTypeSelected))
)
}
}
Template:
<div *ngFor="let item of itemRef | async">
<pre>{{ item | json}}</pre>
</div>
Update: I was able to solve this issue by the following code. Not sure if this is the proper method to solve this.
this.itemRef = combineLatest([this._db.list('/items', ref => ref.orderByChild('group_id').equalTo(this.group_id)).snapshotChanges(), this.itemType.asObservable()]).pipe(
map(results => results[1].map(a => {
const obj = a.payload.val();
return new Item(obj);
}).filter(item=>item.type==results[0])
)
);