AngularJS : How to use one resolve for all the routes of my application

Both @N13 and I could not make @Josh's solution work. But this did work for me:

    module.config(['$routeProvider', function($routeProvider){
        $routeProvider.accessWhen = function(path, route){
            route.resolve || (route.resolve = {});
            route.resolve.language = "something"
            return $routeProvider.when(path, route);
        };
    }]);

use with:

$routeProvider
        .accessWhen('/login', {
           ...
        });

For completeness, here is the whole solution, using angular instead of underscore, with a chainable 'when'. Nothing new in this code, just combined a bunch of the answers above.

var originalWhen = $routeProvider.when;

    $routeProvider.when = function(path, route) {
        route.resolve || (route.resolve = {});
        angular.extend(route.resolve, {
            CurrentUser : function(User) {
                return User.current();
            }
        });

        return originalWhen.call($routeProvider, path, route);
    };

You could always wrap the existing when method on the $routeProvider with your own implementation.

var myModule = angular.module('myModule', ['ngRoute'])
   .config(['$routeProvider', function($routeProvider){

      var originalWhen = $routeProvider.when;

      $routeProvider.when = function(path, route){

         route.resolve = {
            'currentUser':function( UserService){            
              return UserService.getCurrentUser();
            }
         };

         return originalWhen(path, route);
      };   

   }]);

You probably want to add some error checking in there, and use something like underscores defaults method instead of just overwriting the existing resolve property, but at least this way you can guarantee all your routes will have what you want.

It's also easy enough to wrap this up into a helper method.


The @Josh answer is correct, except you have to invoke originalWhen function differently:

originalWhen.call($routeProvider, path, route);

Tags:

Angularjs