AngularJS:身份验证失败时重定向到登录页面

时间:2016-03-28 04:49:10

标签: angularjs

如果密码和用户名不正确,这是重定向ti登录页面的正确方法吗?

 when('/dashboard', {
          resolve:{
            "check": function($location,$rootScope,$cookieStore)
            {
                if(!$cookieStore.get('token'))
                {
                    $location.path("/login");
                }
            }
          },
        templateUrl: 'views/dashboard/index.html',
        //controller: 'AboutCtrl',
        //controllerAs: 'about'
      }

2 个答案:

答案 0 :(得分:1)

你可以做这样的事情

.when('/viewprojects', {
        templateUrl: '/views/projects.html',
        controller: 'ProjectViewController',
        resolve: {
          authenticate: authenticateCb
        }
      })

authenticateCb的位置:

/**
     * A callback to authenticate routes navigation.
     * @param   {Object} Authenticator Authentication service
     * @returns {Object} authenticated promise.
     */
    var authenticateCb = function (AuthenticatorService) {
      return AuthenticatorService.authenticated();
    };

AuthenticatorService如下:

function AuthenticatorService($q, $rootScope, $location, NotifierService, ViewPath) {
    /**
     * Authentics the user on route changes and navigate to corresponding
     * view. If the user is not authenticated then it naviagtes the user
     * to Log in page.
     * @returns {Object} authenticated promise.
     */
    this.authenticated = function () {
      var deferred = $q.defer();
      if ($rootScope.token) {
        deferred.resolve('Authenticated.');
      } else {
        NotifierService.notify('PLEASE_LOGIN_AGAIN', 'error');
        $location.path(ViewPath.LOGIN_PAGE);
        deferred.reject();
      }
      return deferred.promise;
    };
  }

希望这有帮助。

答案 1 :(得分:1)

没有。它应返回promise来解析路由。例如

将在解析中使用该服务的路由配置。

$routeProvider
    .when("/news", {
        templateUrl: "newsView.html",
        controller: "newsController",
        resolve: {
            greeting: function(greetingService){
               return greetingService.getGreeting();
            }
        }
})

以下简单greetingService使用$ q来模拟获取某些数据所需的异步工作。

app.factory("greetingService", function($q, $timeout){
   return {
       getGreeting: function(){
           var deferred = $q.defer();
           $timeout(function(){
               deferred.resolve("Allo!");
           },2000);
           return deferred.promise;
       }
   }
});

这将解决您的路线。

希望它有所帮助。