angular ui-router:在解析中获取 toState 的 $state 信息 [英] angular ui-router: get $state info of toState in resolve
问题描述
更新:从 1.0.0alpha0
开始,这应该可以在 angular-ui-router 中实现.请参阅发行说明 https://github.com/angular-ui/ui-router/release/tag/1.0.0alpha0 和问题 https://github.com/angular-ui/ui-router/issues/1018 我创建的.
Update: this should be possible in angular-ui-router as of 1.0.0alpha0
. See the release notes https://github.com/angular-ui/ui-router/releases/tag/1.0.0alpha0 and the issue https://github.com/angular-ui/ui-router/issues/1018 I created.
我想在处理解析时使用 angular ui-router 访问应用程序导航到的状态名称和其他属性.
I would like to access the state's name and other attributes the app is navigating to using angular ui-router when working on the resolve.
原因:我想在允许应用程序进入该页面之前异步加载一些用户数据(包括他们的访问权限).
The reason: I want load some user data (including their access rights) asynchronously before allowing the app the enter that page.
目前这是不可能的,因为将 $state 注入到 resolve 中指向的是您导航离开表单的状态,而不是您导航到的状态.
Currently this is not possible because injecting $state into the resolve points to the state you're navigating away form, not to the one you're navigating to.
我知道我可以:
- 使用 $rootScope('$stateChangeStart') 在其他地方获取 toState 并将其保存在我的设置服务中.不过我觉得有点乱.
- 将状态硬编码到解析中,但我不想对所有页面重复使用解析
我也在ui-router github上创建了一个问题(如果你有兴趣,请+1!):https://github.com/angular-ui/ui-router/issues/1018
I also created an issue on the ui-router github (Please + 1 if you are interested!): https://github.com/angular-ui/ui-router/issues/1018
到目前为止,这是我的代码.任何帮助表示赞赏!
Here's my code so far. Any help appreciated!
.config(function($stateProvider) {
$stateProvider.state('somePage', {
// ..
resolve: {
userData: function($stateParams, $state, Settings) {
return Settings.getUserData() // load user data asynchronously
.then(function (userData) {
console.log($stateParams);
console.log($state);
// Problem: $state still points to the state you're navigating away from
});
}
}
});
});
推荐答案
Ui-Router 1.x 更新
$provide.decorator('$state', ($delegate, $transitions) => {
$transitions.onStart({}, (trans) => {
$delegate.toParams = trans.params()
$delegate.next = trans.to().name
})
return $delegate
})
Ui-路由器 0.x
你总是可以用 next
和 toParams
属性来修饰 $state
:
Ui-Router 0.x
You can always decorate $state
with next
and toParams
properties:
angular.config(function($provide) {
$provide.decorator('$state', function($delegate, $rootScope) {
$rootScope.$on('$stateChangeStart', function(event, state, params) {
$delegate.next = state;
$delegate.toParams = params;
});
return $delegate;
});
});
并像这样使用:
.state('myState', {
url: '/something/{id}',
resolve: {
oneThing: function($state) {
console.log($state.toParams, $state.next);
}
}
});
这篇关于angular ui-router:在解析中获取 toState 的 $state 信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!