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

Tixeon
  • 930
  • 1
  • 12
  • 27
  • 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](http://stackoverflow.com/questions/16286605/initialize-angularjs-service-with-asynchronous-data) for solutions. – user2943490 Dec 18 '14 at 04:14
  • Have you tried $rootScope.$watch – byrdr Dec 18 '14 at 04: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. – Ben Jacobs Dec 18 '14 at 05:46
  • Thanks @Benmj , I used resolve in controller and it works out for the time being – Tixeon Dec 18 '14 at 08:01

1 Answers1

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.

rishi
  • 1,792
  • 5
  • 31
  • 63
  • does it mean that it wait for the completion of the process in app.run() and then it would start app.controller ? – Tixeon Dec 18 '14 at 05:22