我不确定这是否重复,但我没有找到任何对我有用的东西,所以我发布了这个问题。
我遇到一种情况,在将用户定向到某些路线之前,我需要从数据库获取值,以便我可以决定显示哪些内容。
如果我将 e.preventDefault()
移到 $state.go(..)
之前,那么它可以工作,但不能正常工作。问题是它开始加载默认状态,当它从 http 获得响应时,它才会重定向到 main.home
。假设,如果数据库请求需要 2 秒,那么重定向到 main.home
之前需要 2 秒,这意味着用户在大约 2 秒内看到了不应该看到的内容。
有没有办法在状态更改开始时防止默认并在状态更改结束时重定向用户? 另外,如果我们可以在状态改变开始时阻止默认状态,那么我们如何继续默认状态呢?
(function(){
"use strict";
angular.module('app.routes').run(['$rootScope', '$state', '$http', function($rootScope, $state, $http){
/* State change start */
$rootScope.$on('$stateChangeStart', function(e, to, toParams, from, fromParams){
e.preventDefault();
$http
.get('/url')
.error(function(err){
console.log(err);
})
.then(function(response){
if( response.data === 2 ){
// e.preventDefault()
$state.go('main.home');
}
// direct to default state
})
}
}]);
});
最佳答案
您可以将 resolve
部分添加到 $stateProviderConfig 中。
在解析中,您可以向数据库发出请求并检查所需的条件。如果您不希望用户访问此页面,您可以使用 $state.go() 将他重定向到其他地方。
示例配置:
.state({
name: 'main.home',
template: 'index.html',
resolve: {
accessGranted: ['$http', '$state', '$q',
function($http, $state, $q) {
let deffered = $q.defer();
$http({
method: 'GET',
url: '/url'
}).then(function(data) {
if (data === 2) {
// ok to pass the user
deffered.resolve(true);
} else {
//no access, redirect
$state.go('main.unauthorized');
}
}, function(data) {
console.log(data);
//connection error, redirect
$state.go('main.unauthorized');
});
return deffered.promise;
}
]
}
});
已提供解决
的文档here
请注意,如果您不需要支持IE,您可以使用Promise
对象而不是$q服务。
关于javascript - promise 后 Angular 状态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38453589/