5

UI-Router is different than Angular's ngRoute. It supports everything the normal ngRoute can do as well as many extra functions.

I am changing my Angular app from ngRoute to UI-Router. But I cannot quite figure out how to inject resolve function programmatically - the piece of code that I use outside Controller and config.

So, with standard Angular's ngRoute I can dynamically inject my resolve promise in the Angular run block:

app.run(function ($route) {
  var route = $route.routes['/'];
  route.resolve = route.resolve || {};
  route.resolve.getData = function(myService){return myService.getSomeData();};
});

Now how do I inject resolve promise in a similar way using UI-Router? I tried passing $stateProvider to get access to states but that was failing for me.

angular.module('uiRouterSample').run(
  [          '$rootScope', '$state', '$stateProvider'
    function ($rootScope,   $state, $stateProvider) {

      //$stateProvider would fail
Vad
  • 3,658
  • 8
  • 46
  • 81
  • Can you share the logic of how you are currently deciding what should be resolved for a given route? I think you can take that logic and extract it into a set of UI Router states that will achieve the same result. For example, you can use state parameters in the resolve functions to make them dynamic. – Sunil D. Nov 19 '15 at 20:00

4 Answers4

6

You can use resolve to provide your controller with data before it loads the next state. To access the resolved objects, you will need to inject them into the controller as dependencies.

Let's use a shopping list application as an example. We'll start by defining our application module, and including ui.router as a dependency.:

angular.module('myApp', ['ui.router']);

We now want to define the module that will be specific to the shopping list page of our application. We'll define a shoppingList module, include the states for that module, a resolve for that state, and the controller.

Shopping List Module

angular.module('myApp.shoppingList').config(function ($stateProvider) {

    $stateProvider.state('app.shoppingList', {
        url: '/shopping-list',
        templateUrl: 'shopping-list.html',
        controller: 'ShoppingListController',
        resolve: {
            shoppingLists: function (ShoppingListService) {
                return ShoppingListService.getAll();
            }
        }
    });

});

We now can inject our resolved objects into our controller as dependencies. In the above state, I am resolving an object to the name shoppingLists. If I want to use this object in my controller, I include it as a dependency with the same name.

Shopping List Controller

angular.module('myApp.shoppingList').controller('ShoppingListController', function ($scope, shoppingLists) {
    $scope.shoppingLists = shoppingLists;
});

For additional details read the Angular-UI Wiki, which includes an in-depth guide to using resolve.

anthonysmothers
  • 307
  • 1
  • 6
0

Check the documentation:

Resolve

You can use resolve to provide your controller with content or data that is custom to the state. resolve is an optional map of dependencies which should be injected into the controller.

If any of these dependencies are promises, they will be resolved and converted to a value before the controller is instantiated and the $stateChangeSuccess event is fired.

The resolve property is a map object. The map object contains key/value pairs of:

  • key – {string}: a name of a dependency to be injected into the controller.
  • factory - {string|function}:
    • If string, then it is an alias for a service.
    • Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before the controller is instantiated and its value is injected into the controller.

Examples:

Each of the objects in resolve below must be resolved (via deferred.resolve() if they are a promise) before the controller is instantiated. Notice how each resolve object is injected as a parameter into the controller.

example code for state

$stateProvider.state('myState', {
  resolve:{

     // Example using function with simple return value.
     // Since it's not a promise, it resolves immediately.
     simpleObj:  function(){
        return {value: 'simple!'};
     },

     // Example using function with returned promise.
     // This is the typical use case of resolve.
     // You need to inject any services that you are
     // using, e.g. $http in this example
     promiseObj:  function($http){
        // $http returns a promise for the url data
        return $http({method: 'GET', url: '/someUrl'});
     },

     // Another promise example. If you need to do some 
     // processing of the result, use .then, and your 
     // promise is chained in for free. This is another
     // typical use case of resolve.
     promiseObj2:  function($http){
        return $http({method: 'GET', url: '/someUrl'})
           .then (function (data) {
               return doSomeStuffFirst(data);
           });
     },        

     // Example using a service by name as string.
     // This would look for a 'translations' service
     // within the module and return it.
     // Note: The service could return a promise and
     // it would work just like the example above
     translations: "translations",

     // Example showing injection of service into
     // resolve function. Service then returns a
     // promise. Tip: Inject $stateParams to get
     // access to url parameters.
     translations2: function(translations, $stateParams){
         // Assume that getLang is a service method
         // that uses $http to fetch some translations.
         // Also assume our url was "/:lang/home".
         return translations.getLang($stateParams.lang);
     },

     // Example showing returning of custom made promise
     greeting: function($q, $timeout){
         var deferred = $q.defer();
         $timeout(function() {
             deferred.resolve('Hello!');
         }, 1000);
         return deferred.promise;
     }
  },

example controller, consuming the above resolve stuff

  // The controller waits for every one of the above items to be
  // completely resolved before instantiation. For example, the
  // controller will not instantiate until promiseObj's promise has 
  // been resolved. Then those objects are injected into the controller
  // and available for use.  
  controller: function($scope, simpleObj, promiseObj, promiseObj2, translations, translations2, greeting){
      $scope.simple = simpleObj.value;

      // You can be sure that promiseObj is ready to use!
      $scope.items = promiseObj.data.items;
      $scope.items = promiseObj2.items;

      $scope.title = translations.getLang("english").title;
      $scope.title = translations2.title;

      $scope.greeting = greeting;
  }
})
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • thank you and while it is useful to look at - this is not what I was asking really. I need to assign a resolve promise function inside of RUN block. I cannot touch Controllers. My code above works well with ng-route but my goal is to modify it to use ui-router – Vad Nov 16 '15 at 16:22
  • UI-Router is about states. So resolves belongs to state, not to run phase. If you need to do some stuff in run, you can, but then assign the resut to some Service/Factory to be used later as a placeholder (being Singleton). But the essence of Resolve belongs EXACTLY to state definition. That's how UI-Router is designed ... does it help a bit? or – Radim Köhler Nov 16 '15 at 16:23
  • That's right. So what I really want is to abstract route resolve from controller and inject it into run block where I can resolve the promise (returned data will be stored in my service). My code is ideal example of what I need except that I can no longer use $route. But I do want to use the same logic. – Vad Nov 16 '15 at 16:40
  • I would use abstract state with a resolve. E.g. here http://stackoverflow.com/q/27168835/1679310. And that could be used via view scope inheritance http://stackoverflow.com/q/27696612/1679310. Simply, UI-Router is a state machine. And you should play with to understand it. And use it as is. Resolve and state hierarchy is the way in such scenario, I'd say... – Radim Köhler Nov 16 '15 at 16:43
  • I think I poorly asked my question. Apologies. Imagine you have your ui-router app working. Let's refer to sample UI-Router project app on GitHub (http://angular-ui.github.io/ui-router/sample/#/). Without touching its original code, how can I dynamically inject resolve function for any specified state that I need? This code must be isolated from controllers. Perhaps, Angular Run Block is what can help me (see original code I posted for NG-Route). This code can be a part of JS include script on the page - the key is to add it dynamically after Angular configuration code. – Vad Nov 19 '15 at 15:41
  • Now, you can see, that the way is state resolve. As I told you some time ago... and my links to examples with abstract states should show you how to do it in general (even once) ... check the trick with root state here (and parent: 'root' on any other grand parent of a state family... http://stackoverflow.com/q/28800644/1679310 – Radim Köhler Nov 20 '15 at 07:27
0

You won't have access to $stateProvider in run and I don't think you should be changing the state configuration after creating it (and you might have no way of doing it anyway), why not just add resolve on state creation?

kruczy
  • 791
  • 4
  • 8
  • if it's possible with ngRoute and UI-Router is supposed to be something extra than that, why not possible? Maybe there is another way to inject resolve dynamically. Think of it as an optional plugin/extension code for existing Angular app. That's why I cannot add them into the state configuration in the first place – Vad Nov 19 '15 at 19:20
0

For adding resolve unconditionally to one or several states an abstract state should be used for inheritance:

$stateProvider
.state('root', {
    abstract: true,
    resolve: {
        common: ...
    },
})
.state('some', {
    parent: 'root',
    ...
});

It is the preferred method which requires no hacking.

As for the equivalent of dynamic $route resolver in UI Router, here is a small problem. When a state is registered with state method, it is stored internally and prototypically inherited from the definition, rather than just being assigned to state storage.

Though the definition can be acquired later with $state.get('stateName'), it is not the same object as the one which is being used by the router internally. Due to how JS inheritance works, it won't make a difference if resolve object exists in the state, so new resolver properties can be added there. But if there's no $state.get('stateName').resolve, that's dead end.

The solution is to patch state method and add resolve object to all states, so resolver set can be modified later.

angular.module('ui.router.hacked', ['ui.router'])
.config(function ($stateProvider) {
  var stateOriginal = $stateProvider.state;
  $stateProvider.state = function (name, config) {
    config.resolve = config.resolve || {};
    return stateOriginal.apply(this, arguments);
  }
})

angular.module('app', ['ui.router.hacked']).run(function ($state) {
  var state = $state.get('some');
  state.resolve.someResolver = ...;
});

As any other hack, it may have pitfalls and tends to break. Though this one is very solid and simple, it requires additional unit-testing and shouldn't be used if conventional methods could be used instead.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565