How to assign snap.val() to the global variable?


I want to assign snap.val() to this.Productslike this.Products= snap.val(); but this.Products is undefined in that scope.

    Products: FirebaseListObservable<any>;


     .equalTo('NW1Kq4WB7ReUz2BNknYWML9nF133').on('child_added', function(snap){
              //this.Products= snap.val();

I tried the following code when snap is returned ,but I receive this message — No index defined for uid:


My Firebase database:

"Products" : {
    "-Kbx0i-TFeTyRbNZAZ_8" : {
      "category" : "1",
      "detail" : "xxxxx details",
      "name" : "xxxxx",
      "uid" : "NW1Kq4WB7ReUz2BNknYWML9nF133"

Please help. Thanks.


The directly answer the question you asked, you can use an ES6 arrow function:

let query = this.angularFire.database.list('/Products').$ref.orderByChild('uid')
query.on('child_added', (snap) => this.Products= snap.val());

Or for ES5 compatibility, declare this as a variable:

let self = this;
let query = this.angularFire.database.list('/Products').$ref.orderByChild('uid')
query.on('child_added', function(snap) {
   self.Products= snap.val();

But in reality, this is an XY problem and you don’t want what you think you want here.

What you’ve done is reimplement the list yourself, and defeat the entire purpose of AngularFire2, which handles all this synchronization on your behalf.

Additionally, you’ve mis-used child_added by assigning each record you get back (you get an array of results, not exactly one) to this.products, when you probably wanted to set this.products = [] and then use this.products.push(snap.val()) for each child_added invocation.

So what you really want here, is to use AngularFire’s built-in queries and avoid this entire mess 🙂

this.products = af.database.list('/Products', {
  query: {
    orderByChild: 'uid',
    equalTo: 'NW1Kq4WB7ReUz2BNknYWML9nF133' 

Answered By – Kato

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published