Domanda

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()
                  }
                ]
       }
    });
});
È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top