问题描述
我正在使用 Angular UI 路由器,我想知道是否有人知道使用 resolve
时未解析的承诺是否会泄漏.我们的用例是在某些状态下,我们需要做一些检查,然后在原始状态加载之前转换到不同的 url.
I am using angular UI router and I was wondering if anyone knew whether or not unresolved promises when using resolve
would leak. Our use case is that in certain states, we needed to do some checks and then transition to a different url before the original state loads.
我们处理这个问题的方法是在 resolve
中使用 $location
进行检查和切换 url,并留下未解决的承诺.未解决的承诺用于防止加载原始状态的控制器和模板(否则它们会抛出错误).
The way we handled this was doing the check and switching the url using $location
inside resolve
and leaving an unresolved promise. The unresolved promise was used to prevent the original state's controllers and templates from loading (or else they would've thrown errors).
所以我的问题是,这种留下未解决的承诺的做法会导致泄漏吗?我意识到另一种选择是设置一个长 $timeout
来解决承诺,但如果没有必要,我想避免它.
So my question is, does this practice of leaving unresolved promises cause leakage? I realize an alternative option is to set a long $timeout
for resolving the promises but if its not necessary, I would like to avoid it.
推荐答案
您需要解决或拒绝承诺.我建议在 $stateChangeError
事件侦听器中进行 URL 切换,该事件侦听器会因拒绝承诺而被触发.你可以将reject([data])
中你想去的位置传给监听器.
You would need to resolve or reject the promise. I would suggest that the URL switching would take place in the $stateChangeError
event listener, which would be fired by rejection of the promise. You can pass the location you want to go to in the reject([data])
to the listener.
http://fiddle.jshell.net/L9jxf/2/
一些承诺会在超时后拒绝(模拟服务器调用)
Some promise that will reject after a timeout (simulates server call)
protected: ['$timeout', '$q', function ($timeout, $q) {
var deferred = $q.defer();
$timeout(function () {
deferred.reject({type:'redirect',location:'401'});
}, 1000);
return deferred.promise;
}]
这处理拒绝
app.run(function ($rootScope, $state) {
$rootScope.$on('$stateChangeError', function (e, to, toParams, from, fromParams, error) {
if (error.type === 'redirect') {
$state.transitionTo(error.location);
}
});
});
这篇关于在 AngularUI 路由器中,未解决的承诺是否会泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!