AngularJS Load Data from Service

前端 未结 3 1740
[愿得一人]
[愿得一人] 2020-12-02 14:41

I am having a problem getting data from a service populated into my view. I have a service defined as such

app.factory(\'nukeService\', function($rootScope,          


        
3条回答
  •  余生分开走
    2020-12-02 15:33

    I think this should solve your problem

    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`
    
    }
    

    This is a problem with object reference.

    when you calls nukeService.getNukes() you are getting a reference to a object a then your variable $scope.nukes refers that memory location.

    After the remote server call when you set nukeService.nukes = data; you are not changing the object a instead you are changing nukeService.nukes from referencing object a to object b. But your $scope.nukes does not know about this reassignment and it still points to object a.

    My solution in this case is to pass a object a with property data and then only change the data property instead of changing reference to a

提交回复
热议问题