Recently, I've been experimenting with Angular and struggling to figure it out. The issue I'm facing is with running a $http method in app.run(). This method fetches rooms from the server and initializes it in $rootScope.rooms. However, in the controller, when I try to access this rooms variable, it sometimes returns null because the $http method is asynchronous and the controller loads before it finishes. I'm exploring alternative ways to handle this situation.
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 the rooms variable will be used in other files as well, I prefer not to place the $http method inside every controller unless there are no other options. It would be ideal if I could utilize a service in Angular for this purpose.