authenticating a route in angular

一曲冷凌霜 提交于 2019-12-12 04:34:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!