3

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!

2
  • Do you use ngRoute? Bcoz there's resolve on it that you can use for it. Commented Apr 3, 2014 at 17:31
  • @IqbalFauzi yes, I use ngRoute. Does it mean I need call user.initialize() inside resolve on every controller? Commented Apr 3, 2014 at 17:32

2 Answers 2

3

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.

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

Comments

2

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

Comments

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.