UI-Router:创建规则以防止访问某个状态

UI-Router: create rules to prevent access to a state

UI-router FAQ中,他们提出了一些基于data.rule状态方法来阻止访问某些状态的方法。假设当前用户由某些 $currentUser 服务确定。

然而,这个假设在现实世界的用例中似乎并不成立。因为通常此 $currentUser 服务是以从服务器查询当前用户的方式实现的,并且可能 return 最好的是 promise当前用户的。因此,在 $stateChangeStart 事件触发的那一刻,这个 promise 很可能还没有被解决。

那么,考虑到上述讨论,最好的办法是什么?

注意:

一种解决方法可能是在每个安全状态中包含一个 resolve 属性,其功能是 return 当前用户的承诺。但我真的不喜欢它,因为它有点破坏了我心中的封装。

此处的解决方案是推迟UI-路由器执行 - 直到$currentUser解决。该技术可以从内置功能中获益:deferIntercept(defer)

$urlRouterProvider

The deferIntercept(defer)

Disables (or enables) deferring location change interception.

If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain the current URL), call this method at configuration time. Then, at run time, call $urlRouter.listen() after you have configured your own $locationChangeSuccess event handler.

所有细节都可以在这里找到和观察

  • AngularJS - UI-router - How to configure dynamic views