所以我在我的应用程序中使用了 UI-router,我使用了 $stateChangeStart
监听器显示加载器和 $stateChangeSuccess
然后隐藏加载程序。这样我在状态转换之间就有了一个加载器。
$rootScope.$on('$stateChangeStart',
function (event, toState, toParams, fromState, fromParams) {
///show loader
});
$rootScope.$on('$stateChangeSuccess',
function (event, toState, toParams, fromState, fromParams) {
//hide loader
});
问题:
$stateChangeStart
被称为 B,显示了我的装载机。 $stateChangeSuccess
没有被调用,我的加载器从不隐藏 (因为我们已经在 A 中,所以没有重新加载)那么有没有办法可以监听状态更改取消并隐藏我的加载程序?
更新:
我创建了一个 Plunk .在 plunk 中,我在 B 的解决方案中给出了 10 秒的超时时间。因此,在它解决之前,单击 A。监视控制台以获取状态更改监听器事件。
2015 年 7 月 25 日更新,使用最新的 AngularUI 路由器:
新建 Plunk .
最佳答案
到目前为止,我发现的唯一可持续解决方案是避免使用 ui-sref
.它屏蔽了 $state.go
的返回值在这种情况下这是关键。
诀窍是处理 transition
由 $state.go
返回的 promise
$scope.safeGo = function(stateName){
var transition = $state.go(stateName);
transition.then(function(currentState){
console.log('Transition finished successfully. State is ' + currentState.name);
})
.catch(function(err){
//revert your loader animation here
console.log('Transition failed. State is ' + $state.current.name, err);
})
}
可以通过
$state.transition
访问相同的对象但是在转换之间的属性是 null
并且在任何 $state
的事件中广播它也是null
.因此唯一可靠的选择是获取 $state.go
的返回值.当状态
A
之前被选中 B
已解决transition
promise B
会以理由拒绝 Error: transition superseded
.但是,您仍然需要等到 B.resolve
已完成。如果你想避免这种情况,你必须自己跟踪你的状态,因为过渡到 A
将立即解决(因为当前状态仍然是 A
而 B
正在尝试解决)。更新 plunker
关于angularjs - 如何在 ui-router 中获知状态更改取消?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29071416/