2017-08-27 48 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