Question

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!

Était-ce utile?

La 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.

Autres conseils

I had the same problem. The only solution I found was to create some function in the rootScope and call it from the controller. So the app.run function has inside something like that:

scope.initUser = function () {
   if (!user){
   // create
      user.initialize();
   }
};

And then my controller call it at the beginning:

$rootScope.initUser();

Don't forget to inject the $rootScope into the controller.

This solution doesn't pretend to be elegant but at least it works...

I would appreciate if someone suggest better solution...

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top