我有一个简单的 Angular ui 路由器应用程序:
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('');
$stateProvider
.state('welcome', {
url: '/',
templateUrl: 'components/welcome/welcome.html',
controller: 'MainController',
data: {
auth: true
}
})
.state('courses', {
url: '/courses',
templateUrl: 'components/courses/courses.html',
controller: 'MainController',
data: {
auth: true
}
})
.state('login', {
url: '/login',
templateUrl: 'components/login/login.html',
controller: 'LoginController',
data: {
auth: false
}
})
})
当用户第一次访问浏览器时执行这段代码:
.run(['$rootScope','$http', '$state', 'UserService','userEmailGetService','isUserLoggedService',
function ( $rootScope,$http, $state, UserService,userEmailGetService,isUserLoggedService) {
UserService.CheckIfLogged()
.success(function(data) {
userEmailGetService.setUserEmail(data.email);
isUserLoggedService.setIsLogged(true);
stateCallback();
})
.error(function(data) {
//console.log(data);
isUserLoggedService.setIsLogged(false);
stateCallback();
$state.go("login");
});
this.stateCallback = function() {
$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState) {
alert("Hello");
if (toState.data.auth == true && !isUserLoggedService.getIsLogged()) {
event.preventDefault();
$state.go("login");
}
if (toState.data.auth == false && isUserLoggedService.getIsLogged()) {
event.preventDefault();
$state.go("welcome");
}
});
};
}])
Firefox 中的路由工作正常,但在 Chrome 中,当我登录并转到登录部分时,浏览器应该禁止此重定向并转到欢迎部分,当我在 chrome 中运行程序员控制台时,我在登录时重定向到登录面板 evrythink 工作正确,对我来说很奇怪。当我在 stateChangeStart 中添加警报时,只有当我打开程序员面板时,firefox 才会显示此警报,chrome 不会。
最佳答案
你有一个竞争条件,因为这是异步的:
UserService.CheckIfLogged()
.success(function(data) {
userEmailGetService.setUserEmail(data.email);
isUserLoggedService.setIsLogged(true);
stateCallback();
})
.error(function(data) {
//console.log(data);
isUserLoggedService.setIsLogged(false);
stateCallback();
$state.go("login");
});
这意味着如果路由器在验证码完成之前运行,它将转到登录路由而不是欢迎。 解决方案是使用路由的 resolve 属性,因为它接受 promise ,并将等待异步响应。
关于javascript - Angular ui-router 在 firefox 中工作正常,但在 chrome 中不行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31763797/