角度,数组复制太迟

Angular, array is copied too late

本文关键字:太迟 复制 数组 角度      更新时间:2023-09-26

我有一个回调函数,它用于服务器响应中的数据。在函数中,我试图用数据结果填充数组。我正在填充的数组是在插入到我的主应用程序模块中的不同模块的服务中定义的。我正在使用这个方法来访问我所有控制器中的这个数组,某种全局已知的数组。

angular.module('HighLowTodayApp.services', [])
    .factory('HLTglobalData',['$http',function($http){
       globalData.currentDomainsList = {};
      return {
            currentDomainsList : globalData.currentDomainsList
      }
    });

填充数组的回调函数如下所示:

$scope.getDomainsStatisticsSuccess = function(data){
  HLTglobalData.currentDomainsList = data.slice();
  console.log(JSON.stringify(data));
  console.log(JSON.stringify(HLTglobalData.currentDomainsList));
  //go to showDomainsList page
  $location.path("/showDomainsList");
  
};

问题是,来自"/showDomainsList"路径的控制器的init()函数比HLTglobalData.currentDomainList.的填充更早被触发

我在提到的init()函数中有一个console.log(JSON.stringfy(HLTglobalData.currentDomainsList)),它在控制台中显示了一个空对象{},而且它在前面显示了来自getDomainsStatisticsSuccess函数。

不知何故,在完成阵列复制之前,它的位置发生了更改。我在所有的项目中都使用了这种方法,这是唯一一个这样的地方。

我忘了提到它在Cordova项目中运行的angular应用程序,但我认为这不应该是一个问题。

知道吗?提前感谢!

因此,处理异步内容的最佳方式是Promise。例如:

```

function myService($q){
 var def = $q.defer
 $http().then((data) => def.resolve(data))
 return def
}
function myCtrl($location) {
 myService.then(() => $location.path('/somewhere'))
}

```