James James - 1 month ago 5
AngularJS Question

AngularJS : Injecting Service in app.run

I want to initialize a globle variable "$rootScope.SegmentSelectedGlobal" at the starting of application only.
This globle variable get data from a service.
If i execute service through controller, its working fine.
But when i execute it from App.run, no value is being assinged an d no error is being reported.

Here is the code:

App.run :

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


Service :

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 for your help.

Answer

It returns undefined because at return allSegements allSegements is undefined.

Your using a promise, yet your forgot to return it properly

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;       
    });
}]);

Note if you want to wait for the promised to be resolved before loading your page, use the resolve attribute (available in both 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.
     }];
 }
Comments