Tixeon
Tixeon

Reputation: 930

Async function in angular.run() method has not been executed before controller

Currently i've been playing around with angular and I am finding a hard time in how to figure it out.The problem is that I am running a $http method on app.run(). $http method get rooms from server and initialize it in $rootScope.rooms var. In controller I used this rooms variable . Since the $http method is async and sometimes it got null because the controller loaded before the method is finished . I am trying to handle it in other way .

game.js

angular.module('GameModule', [])
.run([function ("injectors...") {
    $http.get("/rooms").success(function(result){
        $rootScope.rooms = result;

    }).error(function(error){
        console.log('Error fetching rooms');
    });
}])
.controller('GameCtrl', ['$scope', function ($scope) {
    console.log($rootScope.rooms);  
}]);

Since rooms variable will be used in others files too , i don't probably want to put $http method inside every controller unless there are no other ways. If would be nice if i could use sort of angular's service

Upvotes: 0

Views: 1546

Answers (1)

rishi
rishi

Reputation: 1862

This is the normal behavior of angularJs because every REST call is asynchronous. If you want it to be more manageable or behave in a synchronous way then you will have to use "promise" ($q service in angularJs). Please find the code snippet

service code:(which you want to use)

app.lazyload.factory('myService',['$http','$q', function($http,$q) {

        return{
            showAll :function ()
            {
                var deferred = $q.defer();
                $http.post('rest/getAll?cd='+ (new Date()).getTime())
                .success(function(data)
                {
                    deferred.resolve(data);
                })
                .error(function(data)
                {
                    deferred.reject(null);
                    console.log("in error block");
                });

                 return deferred.promise;
            }
        };

    }]);

controller code: (To call service)

    function showAll()
                {
                    var promise = myService.showAll();

                    promise.then(function success(data) {
                        $scope.allitems = data;
                        console.log(data);
                        console.log('$scope.allitems'+$scope.allitems[0].name);

                    }, function error(msg) {
                      console.error(msg);
                    });

                };

I have updated my answer. put the call showAll() at the start of controller body. From your question I assume that you want to load some data at the time of initialization . This approach will get you the same result.

Upvotes: 2

Related Questions