简体   繁体   English

$ routeProvider-为所有路由注入相同的依赖项

[英]$routeProvider - Injecting same dependency for all routes

The following code: 如下代码:

$routeProvider .when("/page1", { controller: "MyController", resolve: {Strategy: "StrategyOne"}}) $ routeProvider .when(“ / page1”,{控制器:“ MyController”,解析:{策略:“ StrategyOne”}})

waits for the Strategy dependency to be resolved before to instantiate the controller "MyController". 在实例化控制器“ 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() 我们将该函数称为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: 我有一个名为“ MainCtrl”的控制器,由于模板中的这一行,所有页面均被调用:

<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). 我认为解决此问题的一种可能方法是,可以在控制器级别(而不是路由级别,因为此依赖项不依赖于特定路由)将Authentication.currentUser()指定为“ MainCtrl”的依赖项。

Thanks for your help guys! 感谢您的帮助!

For those who want to address this with the standard $routeProvider, this is what I came out with: 对于那些想要使用标准$ routeProvider解决这个问题的人,这就是我的想法:

$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. 如果您可以从默认路由器移动到ui-router ,则可以使用嵌套状态进行操作。 Just copying the example from https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#inherited-resolved-dependencies : 只需从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;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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