问题
I need certain routes to require authentication, I am using this module:
https://github.com/enginous/angular-oauth
Which has $scope.authenticate but I am trying to figure out how to access $scope/that function from the $routeProvider. I saw an example call a factory function but that isn't exactly what I am trying to do.
'use strict';
angular.module('app', [
'ngRoute',
'angularOauth',
'googleOauth',
'app.global',
'app.home',
'app.view'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/home/index.html',
controller: 'home'
});
$routeProvider.when('/view', {
templateUrl: 'views/view/index.html',
controller: 'view',
resolve: {
factory: checkAuth
}
}).otherwise({redirectTo: '/'});
$routeProvider.otherwise({redirectTo: '/'});
}]);
var checkAuth = function() {
};
回答1:
The annotation for a resolve is the same dependency injection annotation used anywhere else in Angular. Your logic for authentication should live in a service for testability and reusability, so injecting and calling a method on your service is precisely what you should be doing:
resolve: {
auth: ['AuthenticationService', function (AuthenticationService) {
// Authentication service injected, call your method
return AuthenticationService.isAuthenticated();
}]
}
or
var checkAuth = ['AuthenticationService', function (AuthenticationService) {
// Authentication service injected, call your method
return AuthenticationService.isAuthenticated();
}];
angular.module('app', [
// ...
]).
config(['$routeProvider', function($routeProvider) {
// ...
$routeProvider.when('/view', {
templateUrl: 'views/view/index.html',
controller: 'view',
resolve: {
auth: checkAuth
}
})
// ...
}]);
来源:https://stackoverflow.com/questions/27240186/authenticating-a-route-in-angular