简体   繁体   English

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

[英]How can I resolve data for all states with Angular UI Router?

In my application every route requires that account data has been retrieved from my API prior to rendering. 在我的应用程序中,每个路由都要求在呈现之前从我的API检索帐户数据。 To accomplish this, I do the following using ngRoute: 为此,我使用ngRoute执行以下操作:

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

    next.$$route.resolve.authorizationCheck = function() {
        return deferredAccountData.promise;
    };
});

So before each route, the authorizationCheck resolve, which returns a promise, must resolve. 因此,在每个路由之前, authorizationCheck解析,返回一个promise,必须解决。 This works perfectly. 这非常有效。

I'm now switching to using UI Router, and I need to preserve this functionality. 我现在转而使用UI路由器,我需要保留此功能。 What are some options for accomplishing this? 有什么选择来实现这个目标?

One option I can think of is using nested states and having all routes inherit resolves from a parent state. 我能想到的一个选择是使用嵌套状态并使所有路由继承从父状态解析。 Though I'd prefer to not nest if possible. 虽然如果可能的话我宁愿不窝。 Are there any other options? 还有其他选择吗?

You could resolve the data you want for multiple ui-router states in a parent state. 您可以在父状态下为多个ui-router状态解析所需的数据。 The child state would then have this data as well. 然后,子状态也将具有该数据。

$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) {

  }
})

It would make more sense to have authorization checks within a Service though, so you might want to inject an Auth service in the main controller, and base states and availability on that. 但是,在服务中进行授权检查更有意义,因此您可能希望在主控制器中注入Auth服务,并在此基础上注入状态和可用性。

It all eventually depend on how you organize your routes, since you can inherit routes and provide resolve clause for each child and the parents, but you also have stateChangestart stateChangeSuccess events that will allow you to do something similar to that. 这最终取决于您如何组织路由,因为您可以为每个子节点和父节点继承路由并提供resolve子句,但是您还可以使用stateChangestart stateChangeSuccess事件来执行类似的操作。 for further assistance please provide samples of your routes 如需进一步协助,请提供您的路线样本

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

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