javascript Angular UI-Router - 在解析中返回被拒绝的承诺并不会停止状态转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24812682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular UI-Router - Returning rejected promise in resolve is not stopping state transition
提问by Nick
I am trying to assure that a user is authenticated before allowing them to transition to specific states. As I understand it (after review other posts), a state transition should not occur if the state's resolve returns a rejected promise and the '$stateChangeError' event should be raised. However this is not what I am experiencing.
我试图确保用户在允许他们转换到特定状态之前已经过身份验证。据我了解(在查看其他帖子之后),如果状态的解析返回一个被拒绝的承诺并且应该引发 '$stateChangeError' 事件,则不应发生状态转换。然而,这不是我正在经历的。
Stepping throught the following code, I can see that the deferred promise is rejected but the state transition still occurs and '$stateChangeError' is not triggered. In my module's config I have the following state:
单步执行以下代码,我可以看到延迟的承诺被拒绝,但状态转换仍然发生并且没有触发“$stateChangeError”。在我的模块配置中,我有以下状态:
.state('accounts', {
url: '/Accounts',
controller: 'AccountsController',
templateUrl: 'Scripts/angular/accounts/templates/accounts.tpl.html',
resolve: {
authenticated: ['$q', 'AccountService', function ($q, accountService) {
var deferred = $q.defer();
accountService.userLoggedIn().then(function (loggedIn) {
if (loggedIn) {
deferred.resolve();
} else {
deferred.reject('Not logged in'); <-- This happens
}
return deferred.promise;
});
}]
}
})
In the same module, in the run function I have:
在同一个模块中,在运行函数中我有:
$rootScope.$on('$stateChangeError',
function (event, toState, toParams, fromState, fromParams, error) {
$log.debug(error); <-- This is never called
$state.go('login');
});
What am I missing?
我错过了什么?
回答by Evan Hobbs
You're returning the promise in the wrong place. Authenticated needs to be a function that returns a promise but you're just returning the promise in the the .then() function and then authenticated is returning undefined:
你在错误的地方返回了承诺。Authenticated 需要是一个返回承诺的函数,但您只是在 .then() 函数中返回承诺,然后经过身份验证的返回未定义:
resolve: {
authenticated: ['$q', 'AccountService', function ($q, accountService) {
var deferred = $q.defer();
accountService.userLoggedIn().then(function (loggedIn) {
if (loggedIn) {
deferred.resolve();
} else {
deferred.reject('Not logged in'); <-- This happens
}
});
return deferred.promise;
}]
}
回答by Sava Jcript
You dont need to create new deferred since you already get promise from userLoggedIn():
您不需要创建新的延迟,因为您已经从 userLoggedIn() 获得了承诺:
resolve: {
authenticated: ['$q', 'AccountService', function ($q, accountService) {
return accountService.userLoggedIn().then(function (loggedIn) {
if (loggedIn) {
return loggedIn;
} else {
return $q.reject('Not logged in');
}
});
}]
}

