2013-03-01 90 views
14

我在從填充到我的視圖中的服務中獲取數據時遇到問題。我有一個服務定義爲這樣AngularJS從服務中加載數據

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變量。我可以使用$ rootcope來廣播一個事件並在控制器中監聽它,但這看起來並不是實現這一點的正確方法。我真的很感激任何關於如何以正確方式做到這一點的建議。

回答

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反對b改變a而是要更改nukeService.nukes的對象。但是你的$scope.nukes不知道這個重新分配,它仍然指向對象a

我在這種情況下的解決方案是通過一個對象a與屬性data,然後僅將數據屬性,而不是改變參考更改爲a

+0

這工作,但我可以問爲什麼?我假設它與.data有關,它是json數據的容器,而不是直接傳遞它。順便說一句,謝謝你的及時回覆! – jamesamuir 2013-03-01 16:09:13

+0

如果它正在工作,請將答案標記爲接受 – 2013-03-01 16:17:18

+0

標記爲已回答。謝謝你的解釋。 – jamesamuir 2013-03-01 17:52:17

9

這應該是如下。正如NickWiggill的評論所述,如果我們不返回承諾,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; 
    }); 

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