2

I read this very well though out post

What "things" can be injected into others in Angular.js?

and was curious since I've been told the use the resolve property to make xhr's and to use services to help with these calls. How does the resolve property in this code work? At what point is the $injector invoked?

app.config(function($stateProvider){
  $stateProvider
    .state("eventIndex", {
      url: "/events", 
      views: {
        "main": {
          controller: "EventsCtrl",
          templateUrl: "assets/events/index.html"
        }
      },
      resolve: {
        events: ['EventService', function(Event){
                  return Event.allEvents()
                  }
                ]
       }
    });
});
Community
  • 1
  • 1
jvans
  • 2,765
  • 2
  • 22
  • 23

1 Answers1

1

If your question is: which part of the code is to be invoked by the $injector?

Answer: The config function, the events function (although this is technically declared as an array in your code, from AngularJS's perspective, it's an annotated function), and the EventsCtrl function.

If your question is: when is the resolve() method is invoked?

Answer: ui-router first fires $stateChangeStart and you have a chance to cancel the navigation; if not, it will attempt to resolve all objects declared in resolve by calling $injector.invoke() and getting back promises (if not, they will be wrapped in promises).

Once all promises are resolved (or rejected), ui-router users $injector to invoke onExit of previous state and onEnter of current state before firing $stateChangeSuccess (or $stateChangeError in the case of rejection).

ui-view directive listens for $stateChangeSuccess in order to load view, instantiate controller with $controller provider (which internally uses $injector.instantiate, which in turn uses $injector.invoke, to create the controller instance).

Buu
  • 49,745
  • 5
  • 67
  • 85
  • Ahh ok so the while $injector.invoke() is never run for 'app.config' functions it is run for the resolve property of a config function. Thanks for this answer, learned a lot! – jvans Sep 08 '13 at 13:39
  • 1
    $injector.invoke is indeed used to execute app.config, but that's very early in the cycle (during module loading). Plus the $injector used for config() is a different injector than the normal $injector, it's the provider $injector (so you can only inject providers, not provider instances). State resolution happens much later than that, i.e. after $locationChangeSuccess fired by $location provider. Basically, any method that you declare dependencies is executed with $injector.invoke(). – Buu Sep 08 '13 at 14:50