Search code examples
javascriptangularjscontrollerscoperootscope

Angular.js - In controller wait until service returns value from server


In my Angular.js application I'm stucked with such problem. I have service which is called user and I call it on app.run to get user data from server like so:

app.run(function (user, tracking) {
    user.initialize();
    ... // some other code goes here..
});

This simply calls API route and creates $rootScope.user to be available through all application.

But somehow controller from time to time loads faster then initializing goes.. and $rootScope inside it doesn't contain user object.

function SomeController($scope, $rootScope, $routeParams) {
   console.log($rootScope.user.name); 
   // sometimes returns error -
   // TypeError: Cannot read property 'name' of undefined
}

So how can I force all controllers load only after initializing to $rootScope went well. I don't want to add $watch on user in every controller.. 'cause it looks like bad decision and makes code ugly.

Your suggestions? Thanks!


Solution

  • My solution is to use resolve option of $routeProvider.when() method.

    This will prevent controller to load before request to data is finished:

    $routeProvider.when('/books', { 
      templateUrl: 'books', 
      controller: 'bookCtrl',
      resolve: {
        appUser: function (user) {
           // we're injecting "user" service
           // and initiliazing it (this method returns $promise)
           return user.initialize();
        }
      }  
    });
    

    And inside bookCtrl just injecting appUser as a dependency.