我正在尝试限制用户访问/topics
视图和/question
视图。我在主页上有一个登录表单。我的HomeCtrl具有以下登录功能:
$scope.doLogin = function() {
var user = {
username: $scope.username,
password: $scope.password
}
$http.post('data/user/users.json',
user
).success(function(data, status, headers, config) {
userService.isAuthenticated = true;
userService.username = data.username;
userService.password = data.password;
$location.path('/topics');
console.log('Yay! You logged in.')
}).error(function(data, status, headers, config) {
userService.isAuthenticated = false;
userService.username = '';
userService.password = '';
$scope.errorMessage = 'Failed to log in. Please check username and password.'
});
}
我有一个工厂设置来处理数据的当前状态:
angular.module('myApp.userService', []).
factory('userService', function() {
var credentials = {
username: '',
password: '',
isAuthenticated: false
};
return credentials;
});
这是我的$ routeProvider:
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
}).
when('/topics', {
templateUrl: 'partials/topics.html',
controller: 'TopicCtrl',
//resolve: isAuthenticated
}).
when('/question', {
templateUrl: 'partials/question.html',
controller: 'QuestionCtrl',
//resolve: isAuthenticated
}).
when('/terms', {
templateUrl: 'partials/terms.html',
controller: 'TermsCtrl'
}).
otherwise({
redirectTo: '/'
});
}]);
我已尝试设置如下所示的解决方案:
resolve: {
doLogin: HomeCtrl.doLogin
}
但是会返回以下错误:
由于以下原因无法实例化模块myApp:ReferenceError:HomeCtrl is 没有定义的 在http:// localhost / 2014-02-10 / app / js / app.js:33:18 在Object.d [作为调用]
非常感谢任何帮助 - 我一整天都在看这个,这让我很生气。
答案 0 :(得分:4)
忽略错误,这不是解决此问题的正确方法,因为您无法按照您的想法公开HomeController,而不是正确设置每个依赖项(如$ scope)。
您可以尝试在ng-view
之外定义的某个控制器中捕获$ locationChangeStart,或使用run
块限制登录用户
app.run(function($location, $rootScope, $route, userService) {
$rootScope.$on('$locationChangeStart', function(evt, next, current) {
var nextPath = $location.path(),
nextRoute = $route.routes[nextPath];
if (nextRoute && nextRoute.auth && !loggedIn) {
$location.path("/home");
}
});
});
此外,路线应定义为
when('/topics', {
templateUrl: 'partials/topics.html',
controller: 'TopicCtrl',
auth: true
})