有人可以向我解释为什么,在下面的代码中,$ state.go AND $ location.path()都不起作用?
状态
.state('sheet', {
url: "/",
templateUrl: "views/sheet.html",
controller: 'SheetCtrl',
resolve:
{
loginRequired:
function(RequireLoginService) {
return RequireLoginService.loginRequired();
}
}
})
RequireLoginService
.service('RequireLoginService', function (event, $state, $q, UserService) {
return {
loginRequired: function () {
var deferred = $q.defer();
if (!UserService.isLogged) {
event.preventDefault();
$state.go('login'); // or $location.path('/login');
deferred.reject();
} else {
deferred.resolve()
}
return deferred.promise;
}
}
});
答案 0 :(得分:2)
您需要使用$ timeout通知angularjs更改,而不会导致“$ digest已在进行中”。
.service('RequireLoginService', function (event, $state, $timeout, $q, UserService) {
return {
loginRequired: function () {
var deferred = $q.defer();
if (!UserService.isLogged) {
event.preventDefault();
$timeout(function(){
$state.go('login'); // or $location.path('/login');
});
deferred.reject();
} else {
deferred.resolve()
}
return deferred.promise;
}
}
});
我很高兴它解决了这个问题。