2017-08-27 112 views
1

我有这样的代码:离子3/4角:循环不启动

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']); 
      } 
     } 
    }); 
}); 

而且我很奇怪,为什么在那里,循环就不会启动。当我尝试在那里登录时,我想到了这一点。我的目标是让Firebase数据库中的一些孩子将他们推送到一个数组中。有谁知道我可以做到这一点,或开始循环?

全球套餐:

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

本地套餐:

@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 

系统:

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

你能告诉什么的console.log(snapshot.val())显示绑定正确的? – Nikolaus

+0

我能记录下来。它注销我想要遍历的对象。我无法将其设置为变量。 –

回答

0

您需要使用fat arrow function here.Please下面所显示的尝试。

什么是箭头函数?箭头函数 - 也称为“胖箭头”函数,是用于编写函数表达式的更简洁的语法。 通过使用箭头函数,我们避免输入函数关键字和大括号,它们的{this}从周围拾取,即 意味着我们不再需要使用bind函数来更改函数的上下文 。

使用带有承诺/回调的箭头函数的其他好处是 ,它减少了围绕{this}关键字的混淆。在具有多个嵌套函数的代码 ,它可以是很难保持的 跟踪并记住此背景下

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']); 
       } 
      } 
     }); 
    }); 
+1

这工作。为什么我需要使用这个? –

+0

太棒了。请查看我的帖子中的更新。 – Sampath