使用控制器解决 $routeProvider 中的登录问题 [英] Resolve login in $routeProvider using controller

查看:24
本文介绍了使用控制器解决 $routeProvider 中的登录问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图限制用户对 /topics 视图和 /question 视图的访问.我在主页上有一个登录表单.我的HomeCtrl有如下登录功能:

I'm trying to restrict a user's access to a /topics view and a /question view. I have a login form on the home page. My HomeCtrl has the following login function:

$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.'
        });

    }

我有一个工厂来处理数据的当前状态:

And I have a factory set up to handle the current state of the data:

angular.module('myApp.userService', []).
factory('userService', function() {
    var credentials = {
        username: '',
        password: '',
        isAuthenticated: false
    };

    return credentials;

});

这是我的 $routeProvider:

And this is my $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 [作为调用]

Failed to instantiate module myApp due to: ReferenceError: HomeCtrl is not defined at http:// localhost/2014-02-10/app/js/app.js:33:18 at Object.d [as invoke]

非常感谢任何帮助 - 我一整天都在看这个,这让我很生气.

Any help is greatly appreciated - I've been looking at this all day and it's driving me mad.

推荐答案

忽略该错误,这不是解决此问题的正确方法,因为您无法按照您的想法公开 HomeController,而不是每个依赖项(如 $scope) 正确设置.

Ignoring the error, this would not be a correct way to solve this problem as you cannot expose HomeController as you are thinking and not with every dependency (like $scope) setup correctly.

您可以尝试在ng-view之外定义的一些控制器中捕获$locationChangeStart,或者使用run块来限制登录用户

You can try to capture $locationChangeStart, in some controller that is defined outside the ng-view or use the run block to restrict to login user

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
    })

请参阅此SO 帖子plunkr 获得一个想法.

See this SO post and the plunkr to get a idea.

这篇关于使用控制器解决 $routeProvider 中的登录问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆