为什么我的 $state.go 仅在设置超时内工作
Why my $state.go only working when inside a setTimeout?
当用户键入/general
时,我需要重定向用户/boards
。我正在使用$state.go('boards')
来实现这一点,但即使没有延迟,它也只有在将其包装在setTimeout
函数中时才有效。为什么会有这种行为?
App.randomModule = angular.module('App.randomModule', ['ngRoute', 'ui.router'])
.config(function ($stateProvider){
$stateProvider
.state('general', {
url: '/general',
resolve: {
redirect: function ($state){
// Working
window.setTimeout(function(){
$state.go('boards');
}, 0); // Note there's no delay
// Not working
$state.go('boards');
}
}
})
});
setTimeout(function(){}, 0)
在下一个即时报价中执行该函数。您的决心:在您执行其他操作之前不会调用重定向。
因此,当您处于当前循环中时,您告诉ui-router:$go('/general')
- 所以现在它需要转到常规。但它不会立即这样做,因为它有resolve()
!首先,它尝试解析redirect
对象,然后执行其$go('/general');
因此,您为摘要周期堆叠了一些更改:- 创建 resolve 对象(也许你在那里返回一个承诺,也许是一个值,也许未定义,没关系)- $state.go('/board')- $state.go('/general')
而且(这里的假设),angular 会看到它在挖掘循环中发生变化,并且会看到即使您调用解析,它也不是最后一个要放置的 URL,它会被覆盖。
但是,当您将setTimeout()
放入游戏时,您的go('board')会在摘要循环之后被调用,因此它将执行。
附带说明一下,您可能最好使用 $timeout 而不是 setTimeout。
你为什么要为此使用resolve
?只需注入$urlRouterProvider
并设置重定向规则:
$urlRouterProvider.when('/general', '/boards');
最好使用 ui 路由器事件。有$stateChangeStart可以帮助您。
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
// your logic
if (...) {
event.preventDefault();
}
})
链接: https://github.com/angular-ui/ui-router/wiki#state-change-events
- 为什么页面重新加载会使设置超时无效,以及如何避免
- 立即设置超时
- iOS Safari Javascript设置超时问题
- 如何将嵌套设置超时转换为承诺
- 如何循环设置超时函数
- 关于设置超时/间隔上下文
- 清除设置超时之前的间隔将不起作用
- 在悬停功能中设置超时
- 延迟设置超时()
- 我们是否需要设置超时进行短轮询
- 更合乎逻辑的设置超时例程
- 应设置超时触发多少次
- 如何获得设置超时以从输入中读取值
- 尝试为函数和passvariable设置超时-dos'不起作用
- 清除超时多次设置超时
- Javascript设置超时和重定向-IE冻结
- 当一些文本粘贴到文本框中时(没有设置超时),是否检查数字
- 重置设置超时-javascript
- 间隔/设置超时起点
- 设置超时难度