Search code examples
angularjsroutessimplifyresolve

angularjs simplify $routeprovider resolve


I have multiple routes defined, for example:

$routeProvider
.when('/:locale/pages/:id/edit', {
  templateUrl: 'pages/index.html',
  controller: 'PageEditController',
  resolve: {
    pages: ['pageService', function(pageService){
      return pageService.readyPromise();
    }],
    locales: ['localeService', function(localeService){
      return localeService.readyPromise();
    }],
    template: ['templateService', function(templateService){
      return templateService.readyPromise();
    }]
  }
})

I do really need all 3 of these promises resolved for pretty much every URL I have. It gets rather tedious having to define this for every single route... Plus, when a new service comes along that is also required everywhere, I have to patch all the routes with the new promises.

What I'd like to have for my app, no matter on what URL the user lands first, is to first get all the data preloaded and then display the correct controller, without specifying it for each controller.


Solution

  • Basically you have to create your own version of $routeProvider (simply extend default one), then extend default .when and the final step is extending .resolve method of route param

    Something like this

    var basicResolves = ... // here your basic resolve functions
    
    var myRouteProvider = angular.extend({}, $routeProvider, {
        when: function(path, route) {
            route.resolve = (route.resolve) ? route.resolve : {};
            angular.extend(route.resolve, basicResolves);
            $routeProvider.when(path, route);
            return this;
        }
    });
    

    You will have your default resolves by using myRouterProvider instead of default $routeProvider