Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller is loaded before resolve is resolved in AngularJS

My AngularJS resolve doesn't finish before the controller is loaded.

Background: Say I have a "my profile" page that is requested (user loads website.com/user). I would like to have angular intercept the request and ask for the appropriate data from the server.

The server will reply differently depending on whether the user is logged in/active/etc. I would like angular to get the data from the server before it loads the template, and before it initiates the appropriate controller. So far it does not.

App.js code:

.when('/user',
  {
    templateUrl:'/templates/user',
    controller: 'my_profile',
    resolve: {
        some_cute_function_name: function($timeout){
            $timeout(function(){
                console.log('here123');
            },5)
        }
   }

Meanwhile, controller code:

            console.log('about to update scope');

It turns out that the controller is initiated before the resolve is done. I know this because the greater the number of seconds before the $timeout is done, the more likely I am to see this:

about to update scope
here123

as opposed to the other way around.

Is there any way to ensure that the resolve is resolved before the controller is initiated?

Much appreciated!

like image 706
Adam Avatar asked Dec 23 '13 01:12

Adam


1 Answers

Your resolver needs to return a promise:

  .when('/user',
  {
    templateUrl:'/templates/user',
    controller: 'my_profile',
    resolve: {
        some_cute_function_name: function($timeout){
            return $timeout(function(){
                console.log('here123');
                return { some: 'data' };
            },5);
        }
   }
like image 185
Ben Lesh Avatar answered Nov 07 '22 11:11

Ben Lesh