0

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

4
  • that is the nature of async. You have limited control over when http requests will complete and therefore when that data will be available. See Initialize AngularJS service with asynchronous data for solutions. Commented Dec 18, 2014 at 4:14
  • Have you tried $rootScope.$watch Commented Dec 18, 2014 at 4:19
  • If you're using the angular router, you can define a resolve block so that the page won't navigate to the GameCtrl until the room call is loaded. This is a common way of ensuring that a service is loaded before going to the page that uses it. Commented Dec 18, 2014 at 5:46
  • Thanks @Benmj , I used resolve in controller and it works out for the time being Commented Dec 18, 2014 at 8:01

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

does it mean that it wait for the completion of the process in app.run() and then it would start app.controller ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.