【问题标题】:AngularJs - Array.push() inside $http.get() produces a flawed arrayAngularJs - $http.get() 中的 Array.push() 会产生一个有缺陷的数组
【发布时间】:2019-06-18 13:35:48
【问题描述】:

我无法弄清楚我的代码有什么问题。这似乎是一个javascript问题。

我正在使用 $http.get 加载本地 txt 文件(有不同的方法吗?)。我想将此内容推送到数组中。为了测试,我只是推送任何字符串,以确保它与实际的 txt 文件无关。

 var myArray = [];
 $http.get(localFilePath).then(
        function(success){
            myArray.push("123");
        },
        function(error){
            // other stuff
        });

console.log(myArray);

简单代码不会生成正确的数组。如果我 console.log 创建了数组,这是来自 Chrome 开发工具的屏幕截图:

现在,这看起来像一个正确的数组,但事实并非如此。如果我 console.log(myArray.length)返回 0

下面是使用相同代码 myArray.push("123") outside $http.get() 函数的正确数组的外观:

如果我在 $http.get() 函数中执行此操作,谁能说出这两个数组之间的区别以及为什么第一个数组的创建方式不同?

【问题讨论】:

标签: javascript arrays angularjs http-get


【解决方案1】:

这是一个异步问题。你在 promise 的“resolve”函数之外调用console.log()

var myArray = []
$http.get(localFilePath).then(function(result) {
  myArray.push("123")
})

// outside resolve function     
console.log(myArray)

由于这是一个异步操作,因此仅在 $http.get() 请求完成后(通常在几百毫秒后)才调用解析函数。但是,它不会等待,因此其余代码会继续运行。所以它会启动 get(),然后在 http 请求有机会完成之前立即运行 console.log(),因此在调用 console.log() 时它还没有填充数组。

如果您将 console.log() 放入 resolve 函数中,您会看到数组已正确填充,因为它等待 http 请求完成,填充数组,然后只有 它是否打印了结果。

$http.get(localFilePath).then(function(result) {
  myArray.push("123")

  // inside resolve function     
  console.log(myArray)
})

【讨论】:

    【解决方案2】:

    因为您在数组最有可能获得值之前是 console.logging,并且在控制台内部,chrome 更新数组(因为它是一个引用)而不是长度(因为它是一个原语)。这就是为什么作为数组的一部分,您可以看到正确设置的长度属性。 如果你这样做:

    var myArray = [];
    let $http = { get: () => {
        var p = new Promise((resolve, reject) => {
            setTimeout(() => resolve('hi'), 1000);
        })
        return p;
    }}
     $http.get('').then(
      function(success){
          myArray.push("123");
          console.log(myArray, myArray.length, 'after');
      },
      function(error){
          // other stuff
      }
    );
    console.log(myArray, myArray.length, 'before');

    你可以明白我的意思。

    【讨论】:

    • 我很难理解您代码的第一部分。如何编辑我的代码,以便当我在函数之外进行控制台日志时,数组准备就绪?
    • 你等到它准备好 - 使用 .then 或传入回调
    【解决方案3】:

    我已经了解您的问题并尝试了下面的代码,我得到了相同的数组,这是正确的。您正在分配推送从服务返回的对象而不是 array.Array.push() 将在 $http.get() 服务和 $http.get() 服务之外工作

      var myArray = [];
      $http.get(localFilePath).then(
        function(success){
            myArray.push("123");
           return success
        },
        function(error){
            // other stuff
         return success
        });
    
      console.log(myArray);
      var myArray2 = [];
      myArray2.push("123");
      console.log(myArray2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-12
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      相关资源
      最近更新 更多