mathieu
mathieu

Reputation: 3174

How are UI-Router's resolve function arguments resolved?

I obviously have missed something from UI-Router and/or angular's documentations so, although I will sound stupid, here it is:

In http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider we have an example resolve function:

resolve: {
    myResolve1:
      function($http, $stateParams) {
        return $http.get("/api/foos/"+$stateParams.fooID);
      }
    }

I understand that its return value will be injected into the controller under the name "myResolve1".

What is less clear to me is where the values for the function parameters "$http" and "$stateParams" are coming from. So, where did the caller find the values to give to this function ?

Upvotes: 0

Views: 108

Answers (2)

Justcald
Justcald

Reputation: 41

You can inject anything that you would normally inject into your controller into a resolve function including other resolves. You need to be careful with this because if you are chaining resolves it will take longer for the state to navigate completely therefore rendering your view slower. An example of chaining resolves would look like this.

resolve: {
    loggedIn: function(auth){ return  auth.requireLoggedIn()},
    user: function(loggedIn, auth){return auth.resolveUser()}
}

auth is a service that is part of my angular application and as you can see loggedIn is a resolve that needs to resolve before it can be used to load your user. You could then inject both of those into your controller.

You can put any Angular service, factory, filter or resolve in there.. And I'm sure I'm missing some other core things you can add as well but that's generally what I inject into a resolve. So to answer your question they just come from your Angular application.

Upvotes: 0

Radim Köhler
Radim Köhler

Reputation: 123861

This is a good point, and as discussed for example here

Angularjs ui-router abstract state with resolve

we should use the IoC oriented notation

resolve: {
    dataParent: ['$stateParams', 'ProfileService', function ($stateParams, ProfileService) {
        var username = $stateParams.username;
        return ProfileService.getProfile(username);
    }]
}

The biggest benefit(s) is ... it will work even with minification applied. But mostly, it is now really clearly stated:

there is an array with all required dependency names - and the resolve function as a last argument

Upvotes: 1

Related Questions