How to properly query a Firebase list in AngularFire2?

paweloque picture paweloque · Feb 10, 2017 · Viewed 14.9k times · Source

I'm developing an Angular2 application with Firebase as a backend. On a subpage I want to display some tasks for a given week which is specified by a route parameter.

I'm using a BehaviorSubject as a parameter to the AngularFire2 query the following way:

export class PrepareComponent implements OnInit {

    private routeSub: any;
    weekId = '';

    private weekSubject: BehaviorSubject<any> = new BehaviorSubject('weekId');

    taskTemplates$: FirebaseListObservable<TaskTemplate[]>;

    constructor(private route: ActivatedRoute,
                private router: Router,
                private angularFire: AngularFire) {

        // this.taskTemplates$ = angularFire.database.list("/taskTemplates");

Here is the Firebase query:

        this.taskTemplates$ = angularFire.database.list("/taskTemplates", {
            query: {
                equalTo: this.weekSubject
            }
        });
    }

    ngOnInit() {
        this.routeSub = this.route.params.map(
            (params: Params) => this.weekId = params[ 'weekid' ]
        ).subscribe(
            weekId => this.weekSubject.next(weekId)
        );
    }

    ngOnDestroy() {
        this.routeSub.unsubscribe();
    }
}

Unfortunately, the Firebase taskTemplates$ observable is not returning any data for the given weekId.

I assumed that once the weekId will be set by querying the route parameters, the list would get it as a query parameter and return the data which has: { weekId: actualWeekId, ...}.

EDIT Added an example of data stored in Firebase:

  {
   "-Kc_E0U4UOl9PPtxpzCM" : {
   "description" : "asdfasdf",
   "weekId" : "99f2"
  },
  "-Kc_E3wv3fhpUt56sM4u" : {
    "description" : "another task",
    "weekId" : "99f2"
  }
}

So what I want to do is to get all records for a given weekId

Answer

Rob picture Rob · Oct 11, 2017

If anyone is having a hard time like me nowadays, this might help you guys:

db.list('/items', ref => ref.orderByChild('size').equalTo('large'))

Please refer to https://github.com/angular/angularfire2/blob/master/docs/rtdb/querying-lists.md

for more information!