0

So i am curious when does onDataChange method occur? It seems like it is activated when user add new information or change already existed data.

However, what I am trying to do is that, before adding new data, I want to check if the item is existing in database....if there is an identical item, adding new data won't be done, or if there is no such item, then it should be added to database.

so, my actual question is that, this process "Checking all the database items", can it be done without using onDataChange method?

mark922
  • 1,136
  • 2
  • 11
  • 20
J-Kyu
  • 11
  • 1
  • 2
  • Can you restructure your question and add some sample code with database structure to make it more clear? – mark922 Aug 01 '18 at 08:47

2 Answers2

0

You basically set up a subscription to the "onDataChange" so its actually watching firebase for changes.

But for checking you could literate through the results or do one time query to the exact path your data it held at.

It also may be a better choice to record everything and then remove the data when not needed.

import { AngularFirestore } from 'angularfire2/firestore';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { map } from 'rxjs/operators';
import { Observable, Subscription } from 'rxjs';

import firebase as firebase from 'firebase/app';

private mysubscription: Subscription;

public this.items:any = [];

constructor(
  public _DB: AngularFireDatabase
) {

  try {

//subscription using AngulaFire
this.mysubscription = this._DB.list("myFireBaseDataPath").snapshotChanges().pipe(map(actions => {
    return actions.map(action => ({ key: action.key, val: action.payload.val() }));
  }))
  .subscribe(items => {

    this.items = [];
    this.items = items.map(item => item);

    console.log("db results",this.items);

    var icount=0;

    for (let i in this.items) {

     console.log("key",this.items[i].key);
     console.log("val",this.items[i].val); 
     console.log("----------------------------------);

     //checking if something exists
     if (this.items[i].key == 'SomeNodePath') {
       var log = this.items[i].val;
     }

    }


  } catch (e) {
    console.error(e);
  }


  });


}

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

//or we can do a one time query using just the firebase module

try {


return firebase.database().ref("myFireBaseDataPath").once('value').then(function(snapshot) { return snapshot.val(); })
    .then(res => {

      for (let myNode in res) {


        console.log(res[myNode]);
        console.warn(res[myNode].myChildPath);
        console.log("----------------------------------);

      }

    })
    .catch(error => console.log(error));


} catch (e) {
  console.error(e);
}

//however it may be better practice to log all data and then firebase.database().ref(/logs").remove(); the entire log when not needed

var desc ="abc";

let newPostKey = firebase.database().ref("/logs").push();

newPostKey.set({

  'info': desc,
  'datetime': new Date().toISOString()

});
0

When does onDataChange method occur?

The onDataChange method is called for every change in the database reference it is attached to. It is also called for every visit to the database reference it is attached to. For example,

    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference("some/database/refrence");

    ref.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
      // This method will be fired for any change in the 
         database.getReference("some/database/refrence") part of the database.
      // It will also be fired anytime you request for data in the 
         database.getReference("some/database/refrence") part of the database
      }

      @Override
      public void onCancelled(DatabaseError databaseError) {
        System.out.println("The read failed: " + databaseError.getCode());
      // This method will be fired anytime you request for data in the 
         database.getReference("some/database/refrence") part of the database
         and an error occurred
      }
    });

Before adding new data, I want to check if the item is existing in database....if there is an identical item, adding new data won't be done, or if there is no such item, then it should be added to database.

This can be done by calling the exists() method on the snapshot retrieved from your database query. Check this stackoverflow question Checking if a particular value exists in the firebase database for an answer to that

So, my actual question is that, this process "Checking all the database items", can it be done without using onDataChange method?

No. The onDataChange method is the callback used to retrieve data from the database. Even if you use the equalTo() method on a query, you'll still have to use the onDataChange method.

I am not a Firebaser Specialist tho. There are folks who work at Firebase on here. They could give you more information

PS: Please make your own research on your questions first before asking. Some questions are already answered in the documentation and on stackoverflow.

orimdominic
  • 995
  • 10
  • 23
  • thank you !!! Next time I will double check my question in Stackoveflow before I ask!!!have a wonderful day – J-Kyu Aug 01 '18 at 13:29