silintzir
silintzir

Reputation: 792

Angular UI Router - resolve of child state ALWAYS waits for the parent state to resolve

In the in depth guide of the ui router it has a note in the nested states chapter where it says that

NOTE: The resolve keys MUST be injected into the child states if you want to wait for the promises to be resolved before instantiating the children.

I am using the following example and it seems to me that the child states always waits for the promise of the parent state resolve key to resolve regardless of whether i inject it in the state.

            .state('contacts', {
                templateUrl: 'contacts.html',
                resolve: {
                    // a key that resolves in a second
                    resA: function($q, $timeout) {
                        var deferred = $q.defer();
                        $timeout(function() {
                            deferred.resolve('promise resolved');
                        }, 1000);
                        return deferred.promise;
                    }
                },
                controller: function($scope, resA) {
                    console.log(resA);
                }
            })
            .state('contacts.list', {
                templateUrl: 'contacts.list.html',
                // here i do not inject the resolved key from the
                // parent state but the ctrl still waits 1 second
                // before it executes
                controller: function() {
                    console.log('resolved');
                }
            });

Thus, i cannot understand the note from the official guide.

Upvotes: 2

Views: 986

Answers (1)

user4507618
user4507618

Reputation:

As for controllers - yes, they always wait for their states (or parent states) to resolve. But there might be a situation when your child state also has a resolve object, and some of it's logic depends on parent's resolve keys - in this case you should provide this dependencies explicitly; For example:

.state('contacts', {
  templateUrl: 'contacts.html',
  resolve: {
    // a key that resolves in a second
    resA: function($q, $timeout) {
      var deferred = $q.defer();
      $timeout(function() {
        console.log('I am second, although I am a parent');
        deferred.resolve({id: 'initial'});
      })
      return deferred.promise;
    }
  },
  controller: function($scope, resA) {
    console.log(resA);
  }
})
.state('contacts.list', {
  templateUrl: 'contacts.list.html',
  resolve: {
    // if you do not provide `resA` dependency here
    // your child's `resB` will be the first to resolve
    resB: function() {
      console.log('I am first');
      return 'child promise resolved';
    }
  },
  controller: function() {
    console.log('resolved');
  }
});

Upvotes: 3

Related Questions