Justin Frevert Justin Frevert - 2 months ago 16
TypeScript Question

Ionic 3/ Angular 4: loop does not start

I have this code:

this.LocationTracking.startTracking().subscribe(data => {

firebase.database().ref('campaigns/' + data.results[0].address_components[7].long_name).orderByKey().once("value")
.then(function(snapshot) {
console.log(snapshot.val())
var childData = snapshot.val();
this.fileNamesArr = [];
//The following loop does not start
for (let key in childData) {
if (childData.hasOwnProperty(key)) {
this.fileNamesArr.push(childData[key]['storageFileName']);
}
}
});
});


And I am wondering why the loop in there does not start. I figured this out when I tried to log inside of there. My goal is to get some of the children in the Firebase database and push them to an array. Does anyone know how I can do this, or start the loop?

global packages:

@ionic/cli-utils : 1.2.0
Cordova CLI : 6.5.0
Ionic CLI : 3.2.0


local packages:

@ionic/app-scripts : 1.3.7
@ionic/cli-plugin-cordova : 1.3.0
@ionic/cli-plugin-ionic-angular : 1.3.0
Cordova Platforms : android 6.1.2 ios 4.1.1 windows 4.4.3
Ionic Framework : ionic-angular 3.3.0


System:

Node : v7.7.1
OS : macOS Sierra
Xcode : Xcode 8.3.3 Build version 8E3004b
ios-deploy : not installed
ios-sim : 5.0.13

Answer Source

You need use fat arrow function here.Please try as shown below.

What Are Arrow Functions? Arrow functions – also called “fat arrow” functions, are more concise syntax for writing function expressions. By using arrow functions, we avoid typing the function keyword and curly brackets, their {this} is picked up from surroundings, that means we are no longer need to use bind function to change the context of the function.

The other benefit of using arrow functions with promises/callbacks is that it reduces the confusion surrounding the {this} keyword. In code with multiple nested functions, it can be difficult to keep track of and remember to bind the correct this context

this.LocationTracking.startTracking().subscribe(data => {
    firebase.database().ref('campaigns/' + data.results[0].address_components[7].long_name).orderByKey().once("value")
          .then((snapshot) => {
            console.log(snapshot.val())
            var childData = snapshot.val();
            this.fileNamesArr = [];
            //The following loop does not start
            for (let key in childData) {
              if (childData.hasOwnProperty(key)) {
              this.fileNamesArr.push(childData[key]['storageFileName']);
              }
            }
        });
    });