Ad

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

Ad

Answer

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();
Ad
source: stackoverflow.com
Ad