AngularJS:在app.run中注入服务

时间:2016-10-05 13:35:25

标签: javascript angularjs angularjs-directive angularjs-scope

我想在应用程序启动时初始化一个全局变量“$ rootScope.SegmentSelectedGlobal”。 这个全局变量从服务中获取数据。 如果我通过控制器执行服务,它的工作正常。 但是当我从App.run执行它时,没有任何值被报告,并且没有报告错误。

以下是代码:

App.run:

 app.run(['$rootScope','DashboardService', function($rootScope,DashboardService) {
                    $rootScope.SegmentSelectedGlobal = DashboardService.getSegments();
                }]);

服务:

app.service("DashboardService",function($q,$http,errorMessages){
       var allSegements = [];
        return {
                // For selected Only
                getSegments : getSegments
            }
         function getSegments(){
                var deferred = $q.defer();
                $http({
                    url: "/getAllSegments",
                    method: "GET"
                }).success(function (data, status, headers, config) {
                    deferred.resolve(data);
                    allSegements = data;
                }).error(function (data, status, headers, config) {
                    //logger.logError('Error while retrieving Versions details');
                     allSegements = null;
                });
                return allSegements;
            }
    });

Thanx求助。

1 个答案:

答案 0 :(得分:0)

返回undefined,因为return allSegements allSegements未定义。

您使用了承诺,但忘了将其妥善归还

app.service("DashboardService",function($q,$http,errorMessages){
       var allSegements = [];
        return {
                // For selected Only
                getSegments : getSegments
            }
         function getSegments(){
                var deferred = $q.defer();
                $http({
                    url: "/getAllSegments",
                    method: "GET"
                }).success(function (data, status, headers, config) {
                    deferred.resolve(data);
                    allSegements = data;
                }).error(function (data, status, headers, config) {
                    //logger.logError('Error while retrieving Versions details');
                     deferred.reject();//--------- REJECT IF ERROR
                });
                return deferred.promise;//------- RETURN THE PROMISE
            }
    });

   app.run(['$rootScope','DashboardService',function($rootScope,DashboardService) {
    // use then to get the data from your promise ince it's ready
    DashboardService.getSegments().then(function(data){
            $rootScope.SegmentSelectedGlobal = data;       
    });
}]);

请注意,如果您想在加载页面之前等待承诺得到解决,请使用resolve属性(在ngRoute / ui-router中均可用):

 resolve:{
     segments:['DashboardService', function(DashboardService){
           return DashboardService.getSegments();//we return the promise, the resolve parameter will take the result, in case of error page won't be loaded.
     }];
 }