Olivier Pichon
Olivier Pichon

Reputation: 313

$routeProvider - Injecting same dependency for all routes

The following code:

$routeProvider .when("/page1", { controller: "MyController", resolve: {Strategy: "StrategyOne"}})

waits for the Strategy dependency to be resolved before to instantiate the controller "MyController".

In my application I have a function which returns a promise, which when resolved, gives the current user. Let's called that function Authentication.currentUser()

I would like all the pages of my app to wait for that promise to be resolved before to render a page. I could happily add a line for each route declaration but I would rather avoid duplication.

I have a controller called 'MainCtrl' which is called for all pages thanks to this line in my template:

<html ng-app="clientApp" ng-controller="MainCtrl">

I think one possible way to address this would be if it was possible to specify Authentication.currentUser() as a dependency of "MainCtrl" at the controller level (not at the route level because this dependency does not depend on a particular route).

Thanks for your help guys!

Upvotes: 2

Views: 261

Answers (2)

Olivier Pichon
Olivier Pichon

Reputation: 313

For those who want to address this with the standard $routeProvider, this is what I came out with:

$rootScope.$on('$routeChangeStart', function (event, next, current) {
  if (!next.resolve){ next.resolve = {} }
  next.resolve.currentUser =  function(Authentication){
    return Authentication.currentUser();
  };
});

Upvotes: 1

Michal Charemza
Michal Charemza

Reputation: 27012

If you can move from the default router, to ui-router, then you can do this with nested states. Just copying the example from https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#inherited-resolved-dependencies :

$stateProvider.state('parent', {
  resolve:{
     resA:  function(){
        return {'value': 'A'};
     }
  },
  controller: function($scope, resA){
      $scope.resA = resA.value;
  }
})
.state('parent.child', {
  resolve:{
     resB: function(resA){
        return {'value': resA.value + 'B'};
     }
  },
  controller: function($scope, resA, resB){
      $scope.resA2 = resA.value;
      $scope.resB = resB.value;
  }

Upvotes: 1

Related Questions