【问题标题】:Ionic 3/ Angular 4: loop does not startIonic 3/ Angular 4:循环不启动
【发布时间】:2018-02-05 03:50:03
【问题描述】:

我有这个代码:

    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

【问题讨论】:

  • 你能显示,console.log(snapshot.val()) 显示什么?
  • 我能够记录下来。它会注销我试图遍历的对象。我无法将其设置为变量。

标签: angular cordova typescript ionic3


【解决方案1】:

您需要在这里使用fat arrow function。请尝试如下所示。

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

使用带有承诺/回调的箭头函数的另一个好处是 它减少了围绕 {this} 关键字的混淆。在代码中 使用多个嵌套函数,可能很难跟踪 并记得绑定正确的 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']);
              }
            }
        });
    });

【讨论】:

  • 太棒了。请查看我帖子中的更新。
猜你喜欢
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 2018-04-10
  • 2017-09-09
  • 2018-02-10
  • 2019-09-25
相关资源
最近更新 更多