问题
In UI-router FAQ, they suggested some way for preventing access to some states based on data.rule
method of states. Assuming current user is determined by some $currentUser
service.
However this assumption doesn't seem to be true in real world use cases. Because normally this $currentUser
service is implemented in a way that it queries current user from the server and probably the best it can return is a promise
of the current user. Therefore, at the moment that $stateChangeStart
event is triggered, it's quite possible for this promise to not be resolved yet.
So what's the best thing to do, considering the above discussion?
NOTE:
One workaround might be to include a resolve
property in every secured state, with a function that returns the promise of the current user. But I really don't like it because it kinda breaks encapsulation in my mind.
回答1:
Solution here would be to postpone UI-Router execution - until $currentUser
is resolved. The technique could profit from built in feature: 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.
All the details could be found and observed here
- AngularJS - UI-router - How to configure dynamic views
来源:https://stackoverflow.com/questions/32611458/ui-router-create-rules-to-prevent-access-to-a-state