我正在使用this tutorial来确定我正在使用的Web应用程序的身份验证系统。我正在使用ui-router的StateProvider并解析系统,如果用户尝试访问需要身份验证的页面之一,则将用户重新路由到主页。一切似乎都在工作,除了解析部分似乎并未真正在工作-即我的身份验证返回了被拒绝的诺言,尽管如此,尽管页面应该存在某种错误,但页面加载还是正常的。我究竟做错了什么?

app.states.js

angular
    .module('app')
    .config(routeConfig);

/** @ngInject */
function routeConfig($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/');

  // checks if user is logged in or not
  // passes back rejected promise if not, resolved promise if true
  function authenticated(authFactory, $q) {
    var deferred = $q.defer();
    authFactory.authenticate()
      .then(function(authenticate) {
        if (authenticate.data === 'true') {
          deferred.resolve();
        } else {
          deferred.reject();
        }
      });
    return deferred.promise;
  }

  // every new state that should include a sidebar must have it as a view
  $stateProvider
    .state('dashboard', {
          url: '/dashboard/',
          views: {
            'sidebar': {
              templateUrl: 'app/components/navbar/sidebar.html',
              controller: 'SidebarController as vm'
            },
            'content': {
              templateUrl: 'app/components/authenticated/dashboard.html',
              controller: 'DashboardController as vm'
            }
          },
          resolve: {
            authenticated: authenticated
          }
        })


app.run.js

function runBlock($rootScope, $log, $state) {
    $rootScope.$on('$stateChangeError', function () {
      // Redirect user to forbidden page
      $state.go('forbidden');
    });
  }


auth.factory.js

“使用严格”;

angular
  .module('app')
  .factory('authFactory', authFactory);

authFactory.$inject = ['$http', '$cookies'];

function authFactory($http, $cookies) {
  var _token;
  var service = {
    authenticate: authenticate
  };
  return service;

  // used to prevent user from accessing pages that they shouldn't have access to
  // this is used exclusively in app.routes.js/app.states.js
function authenticate() {
     // gets user's token from cookies, if no cookie, _token will be blank and server will return 403
    // this part might be redundant with other functions, but I left it in for now just to make sure
    if ($cookies.getObject('user')) {
      _token = $cookies.getObject('user').token;
    } else {
      _token = '';
    }
    var request = $http({
      method: 'POST',
      url: 'http://localhost:8080/checkToken',
      headers: {'x-auth-token': _token},
      transformResponse: function(data) {
        return data;
      }
    });
    return request;
  }
}

最佳答案

您需要在功能之外放置return deferred.promise,以便可以正确返回promise。



function authenticated(authFactory, $q, $log) {
  var deferred = $q.defer();
  authFactory.authenticate()
  .then(function(authenticate) {
    if (authenticate.data === 'true') {
      deferred.resolve();
    } else {
      deferred.reject();
    }
  });
  return deferred.promise; //placed outside function
}

10-06 07:33
查看更多