如何使用Angular UI路由器解析所有状态的数据?

Cha*_*son 4 javascript angularjs angular-ui-router

在我的应用程序中,每个路由都要求在呈现之前从我的API检索帐户数据.为此,我使用ngRoute执行以下操作:

$rootScope.$on('$routeChangeStart', function(event, next, current) {
    next.$$route.resolve = next.$$route.resolve || {};

    next.$$route.resolve.authorizationCheck = function() {
        return deferredAccountData.promise;
    };
});
Run Code Online (Sandbox Code Playgroud)

因此,在每个路由之前authorizationCheck,必须解决返回promise的resolve.这非常有效.

我现在转而使用UI路由器,我需要保留此功能.有什么选择来实现这个目标?

我能想到的一个选择是使用嵌套状态并使所有路由继承从父状态解析.虽然如果可能的话我宁愿不窝.还有其他选择吗?

Hyr*_*yra 5

您可以在父状态下为多个ui-router状态解析所需的数据.然后,子状态也将具有该数据.

$stateProvider
.state('app', {
  url: "/",
  resolve: {
    authorizationCheck: function() {
       // Do your API checks or whatever
    }
  }
})
.state('app.somepage', {
  url: "/somepage",
  templateUrl: "partials/some.page.html",
  controller: function($scope) {

  }
})
Run Code Online (Sandbox Code Playgroud)

但是,在服务中进行授权检查更有意义,因此您可能希望在主控制器中注入Auth服务,并在此基础上注入状态和可用性.