AngularJS从服务加载数据

时间:2013-03-01 15:45:36

标签: javascript angularjs service load

我在填充到我的视图中的服务中获取数据时遇到问题。我有一个定义为此类的服务

app.factory('nukeService', function($rootScope, $http) {
    var nukeService = {};

    nukeService.nuke = {};

    //Gets the list of nuclear weapons
    nukeService.getNukes = function() {
        $http.get('nukes/nukes.json')
            .success(function(data) {
                nukeService.nukes = data;
            });

        return nukeService.nukes;
    };

    return nukeService;
});

和我的控制器

function NavigationCtrl($scope, $http, nukeService){



    /*$http.get('nukes/nukes.json').success(function(data) {
        $scope.nukes = data;
    });*/

    $scope.nukes = nukeService.getNukes();

}

如果我使用来自控制器的$ http.get数据填充正常,但是,如果我尝试从服务调用数据,我什么也得不到。我知道查询是异步的,但是我很难理解在返回数据后如何填充$ scope变量。我可以使用$ rootscope来广播一个事件并在控制器中监听它,但这似乎不是完成此任务的正确方法。我真的很感激有关如何以正确的方式做到这一点的任何建议。

3 个答案:

答案 0 :(得分:27)

我认为这应该可以解决你的问题

app.factory('nukeService', function($rootScope, $http) {
    var nukeService = {};

    nukeService.data = {};

    //Gets the list of nuclear weapons
    nukeService.getNukes = function() {
        $http.get('nukes/nukes.json')
            .success(function(data) {
                nukeService.data.nukes = data;
            });

        return nukeService.data;
    };

    return nukeService;
});

function NavigationCtrl($scope, $http, nukeService){

    $scope.data = nukeService.getNukes();

    //then refer to nukes list as `data.nukes`

}

这是对象引用的问题。

当您致电nukeService.getNukes()时,您将获得对象a的引用,那么您的变量$scope.nukes将引用该内存位置。

设置nukeService.nukes = data;后远程服务器调用后,您没有更改对象a,而是将nukeService.nukes从引用对象a更改为对象b }。但是您的$scope.nukes不了解此重新分配,但仍指向对象a

我在这种情况下的解决方案是传递一个带有a属性的对象data,然后只更改数据属性,而不是更改对a的引用

答案 1 :(得分:9)

这应该如下。正如NickWiggill的评论所提到的,如果我们不返回promise,undefined将被分配给nukeService.data。

app.factory('nukeService', function($rootScope, $http) {
    var nukeService = {};
    //Gets the list of nuclear weapons
    nukeService.getNukes = function() {
       return $http.get('nukes/nukes.json');
    };

    return nukeService;
});


  function NavigationCtrl($scope, $http, nukeService){
     nukeService.getNukes().then(function(response){

        $scope.data = response.data;
    });

   }

答案 2 :(得分:3)

我所做的是直接从服务公开数据,并有一个初始化这些数据的方法。这有什么问题?

服务:

app.factory('nukeService', function($scope, $http) {
    var data = {};
    data.nukes = [];

    //Gets the list of nuclear weapons
    var getNukes = function() {
        $http.get('nukes/nukes.json').success(function(data) {
                data.nukes = data;
        });
    };

    // Fill the list with actual nukes, async why not.
    getNukes();

    return {
        data : data
        // expose more functions or data if you want
    };
});

控制器:

function NavigationCtrl($scope, nukeService){
     $scope.data = nukeService.data;
     //then refer to nukes list as `$scope.data.nukes`
}