$ rootScope属性值在服务中未定义

时间:2015-08-02 17:23:39

标签: angularjs angular-services angularjs-rootscope

我在数据库中有一个表,在我的网站上发生任何其他事情之前我需要访问该表。我得到的价值,我将使用所有不同的控制器,指令,服务等。我认为存储这些值的最佳位置将在$rootScope所以为此,我做了以下:

obApp.run(function($rootScope, ngProgress, $timeout) {
  $.post('phpProcessingPage', function(data){
   $rootScope.domains = JSON.parse(data); //this "domains" property is what i'm interested in
  })
})

我毫不费力地回到了域名,所以一切都很好。问题是,当我将$rootScope注入服务时:

obApp.factory('requestOrigin', ['$rootScope', function($rootScope){
   console.log($rootScope.domains); //this is undefined at this point
   return $rootScope.domains; //returns undefined
}]);

预计在服务代码执行后响应将会出现,没有任何内容。

问题是,我在多个控制器中使用该工厂代码,并且我不知道如何延迟它的执行,以便等待我从ajax调用中获取数据。

我尝试过做广播,但我无法(我知道)延迟工厂的retun,即使在某些时候我确实得到了结果。我怎么会解决这个问题呢?

解答:

为此废弃$ rootScope的用法。我使用服务返回结果的控制器如下所示:

oApp.controller(['serviceName', function(serviceName){
    serviceName.then(function(response){
      //here i have the data from the ajax call, the service made
      //other things to do
    });
}]);

服务看起来像这样:

obApp.factory(['serviceName','$http', function(serviceName, $http){
    return $http.post('phpProcessingPage.php', {cache: true});
}]);

2 个答案:

答案 0 :(得分:2)

我说你需要使用promises重新设计这个小东西。

使用服务存储和返回此数据,您可以通过控制器/指令等执行以下操作:

DomainService.getDomains().then(function () {
    // Do whatever you need, here you'll have the data
});

现在服务应该返回数据,或者在应用程序第一次运行时没有从服务器获取数据:

// Domain service
var domains;

var getDomains = function () {
    // using angular's $q service
    var deferred = $q.defer();

    if (domains) {
        // returns the data without going to the server
        deferred.resolve(domains);
    }  
    else {
        // fetches the data the first time, also notice angular's $http service
        $http.post('phpProcessingPage', data).then(function(response)
            domains = response;
            deferred.resolve(domains);
        });
    }

    return deferred.promise;
}

答案 1 :(得分:0)

您应该使用angular $ http而不是使用jquery $ service,它会返回您可以附加到范围的promise。根据定义的承诺会立即定义,并且当承诺得到解决时,您的范围将被填充。在角度模板的顶部完全理解promises,并且一旦准备就会在视图中显示你的模型。

相关问题