Search code examples
javascriptfirebaseionic-frameworkfirebase-realtime-databaseangularfire2

Ionic How to Pass variable to firebase equalTo method


I have already managed to fetch data form firebase.problem is when i'm going to filter data according to the id it doesn't work.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AngularFireDatabase, AngularFireList ,} from 'angularfire2/database';

import { Observable } from 'rxjs'
import { query } from '@angular/core/src/render3';
import { Key } from 'protractor';


class postview {
  constructor(public title) { }
}

@Component({
  selector: 'app-news-view',
  templateUrl: './news-view.page.html',
  styleUrls: ['./news-view.page.scss'],
})
export class NewsViewPage implements OnInit {

  id: string;



  public books: AngularFireList<postview[]>;
  itemlol: Observable<any>;
  posts: Observable<any[]>;

    constructor(private route: ActivatedRoute  , db: AngularFireDatabase) {
      let idp :string = this.id;
      this.posts = db.list('Posts' ,ref => {
        return ref.orderByChild('Post_Id').equalTo(idp)       
            }).valueChanges();

           // this.itemlol= db.object('Posts').valueChanges();
      }


  ngOnInit() {
    this.id = this.route.snapshot.paramMap.get('id');



    console.log(this.id);

    console.log(this.posts);


  }



}

in the section return ref.orderByChild('Post_Id').equalTo(idp) I need to pass variable in equalTo(). It should change according to the user instructions

Example

equalTo(01)
equalTo(02)

This is my firebase database:

This is my firebase database


Solution

  • The constructor is called before ngOnInit so the value for this.id will be undefined at the time of the query.

    You should get the Parameters in the constructor

     this.id = this.route.snapshot.paramMap.get('id');
     let idp :string = this.id;
     this.posts = db.list('Posts' ,ref =>  ref.orderByChild('Post_Id').equalTo(idp)     ).valueChanges();