2016-03-28 15 views
0

パスワードとユーザー名が間違っている場合は、これをti loginページをリダイレクトする正しい方法ですか?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

あなたはauthenticateCbがあるこの

.when('/viewprojects', { 
     templateUrl: '/views/projects.html', 
     controller: 'ProjectViewController', 
     resolve: { 
      authenticate: 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(); 
      } 
     } 
}) 

いくつかのデータをフェッチするために必要な非同期作業をシミュレートするために、$ qを使用して次のような単純なgreetingService

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

これでルートが解決されます。

希望します。

関連する問題