2016-03-28 72 views
0

如果密码和用户名不正确,这是重定向ti登录页面的正确方法吗?AngularJS:验证失败时重定向到登录页面

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

回答

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

不会。它应该返回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; 
     } 
    } 
}); 

这将解决您的路线。

希望它有帮助。

相关问题