简体   繁体   中英

$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!

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();
  };
});

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;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM