Resolve login in $routeProvider using controller

2019-07-08 02:11发布

问题:

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;

});

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: '/'
    });
}]);

I've tried setting up a resolve like the following:

resolve: {
    doLogin: HomeCtrl.doLogin
  }

But that returns the following error:

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.

回答1:

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.

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

Also the routes should be be defined as

 when('/topics', {
        templateUrl: 'partials/topics.html', 
        controller: 'TopicCtrl',
        auth: true
    })

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