简体   繁体   English

角度解析所有状态

[英]Angular one resolve for all states

I got a routeProvider for my states. 我有一个州的routeProvider。

$routeProvider.
      when("/register",{
        templateUrl: "templates/register.html",
        controller: "RegisterCtrl",
        resolve: {
          user: function(Auth) {
            return Auth.resolveUser();
          }
        }
      }).
      when("/home",{
        templateUrl: "templates/home.html",
        controller: "HomeCtrl",
        resolve: {
          user: function(Auth) {
            return Auth.resolveUser();
          }
        }
      }). .... [.....]

Every state got a promise which resolves, when user-state is loggedIn. 当用户状态登录时,每个状态都会解决。 Then the code of the different controllers is executed. 然后执行不同控制器的代码。 Now I want to have a mainController for the navigation bar, which should be present on all sites. 现在,我想要一个用于导航栏的mainController,它应该出现在所有站点上。 The controller needs the userdata for checking for new messages etc. 控制器需要用户数据来检查新消息等。

Now: how is it possible to define the resolve globally in a root state (so i can access the userdata in the root controller for all sites) and all the other controllers execute their code only, if the promise from this roote state is resolved? 现在:如何在根状态下全局定义解析(以便我可以访问所有站点的根控制器中的用户数据),并且所有其他控制器仅在解决了该根状态下的诺言后才执行其代码?

I hope I formulated my question understandable... 我希望我提出的问题可以理解...

I think you're looking for something like $routeChangeStart , that is a way to execute something you want everytime the user changes his route inside your web app. 我认为您正在寻找类似$routeChangeStart东西,这是一种每次用户在Web应用程序中更改其路线时都执行所需内容的方法。 Take a look at Route and this other question from stackoverflow. 看看路线这个从计算器等问题。 Hope it helps. 希望能帮助到你。

You can do this by defining your routes outside of the $routeProvider.when statements: 您可以通过在$routeProvider.when语句之外定义路由来做到这一点:

var routes = [
  {
    url: "/register",
    config: {
      templateUrl: "templates/register.html",
      controller: "RegisterCtrl"
    }
  },
  {
    url: "/home",
    config: {
      templateUrl: "templates/home.html",
      controller: "HomeCtrl"
    }
  }
];

Then iterating through your routes to extend the resolve property before registering them with the $routeProvider : 然后遍历您的路由以扩展resolve属性,然后$routeProvider注册它们:

angular.forEach(routes, function (route) {
  var url = route.url;
  var routeConfig = route.config;

  routeConfig.resolve = angular.extend(routeConfig.resolve || {}, {
    // add your global resolves here
    user: function(Auth) {
      return Auth.resolveUser();
    }
  });

  $routeProvider.when(url, routeConfig);
});

Your Auth.resolveUser() should be responsible for returning the fulfilled promise if it was already resolved previously. 如果以前已经解决过诺言,那么您的Auth.resolveUser()应该负责返回诺言。

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

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