在异步方法中为数组赋值

时间:2015-11-13 08:52:44

标签: javascript arrays angularjs asynchronous

(注意:这是AngularJs,但应该是"标准" Javascript-Issue)

我使用以下方法读取角度控制器内的json文件的内容:

$http.post(apiUrl + 'data.php?select', {directory: "customers", file: "john"})
.success(function (data) {
   $scope.customers= data;
})

(php - 函数只返回一个(有效的)JSon-Array)。

这按预期工作;内容存储在$ scope.customers

因为在不同的地方需要这种行动,我决定为此写一项服务:

myApp.factory('util', function ($http) {
    return {
        getFile:function(directory, file, target) {
            $http.post(apiUrl + 'data.php?select', {directory: directory, file: file})
                .success(function (data) {
                    target = data;
                });
        }
    };

然后按照以下方式调用此方法:

util.getFile("customers","john",$scope.customers);

但是这不起作用($ scope.customers保持为空)。

在深入研究之后我明白这不能以这种方式工作,因为数组不是通过引用而是通过值传递的。

但还有另一种方法可以达到我想要的目的吗?

1 个答案:

答案 0 :(得分:2)

我认为问题是目标现在是一个局部变量,因为javascript总是按值传递,所以在这种情况下,target引用了像$ scope.customers这样的同一个对象。但是覆盖目标不会覆盖$ scope.customers,然后target只会指向另一个对象。

您应该使用.then(result)设置变量:

myApp.factory('util', function ($http) {
    return {
        getFile:function(directory, file, target) {
            return $http.post(apiUrl + 'data.php?select', {directory: directory, file: file})
        }
    };

并用

调用它
util.getFile("customers","john").then(function successCallback(response) {
  // this callback will be called asynchronously
  // when the response is available
  $scope.customers = response.data;
}, function errorCallback(response) {
  // called asynchronously if an error occurs
  // or server returns response with an error status.
  console.log("Error getting customers")
});

这也清楚表明util.getFile是一个异步函数,你可以在这里放置代码,当结果可用时执行。

注意:另一种替代方法是覆盖对象的属性(但我更喜欢上面的方法):

myApp.factory('util', function ($http) {
    return {
        getFile:function(directory, file, target) {
            $http.post(apiUrl + 'data.php?select', {directory: directory, file: file})
                .success(function (result) {
                    target.data = result.data;
                });
        }
    };
相关问题