2017-10-14 98 views
0

我想呼籲路線變化的服務,將檢查接入和訪問是否得到true將打開路徑,如果沒有,會去設置路線UI路由器不會讓我回去解決狀態

app.js:

 .state('home', { 
      url: '/home', 
      templateUrl: 'home.html', 
      controller: 'homeController', 
      resolve: { 
       access: function(AuthService) { 

        return AuthService.getAccess(); 
       } 
      } 
     }) 

在我homeCtrl:

app.controller('homeController', function ($scope, $timeout, $state, UserService, GroupService, SiteService, HomeService, AuthService, access) { 


    // Check access: if true init route, else go to settings 
    if(access) { 
     Collections.init(); 
    } else { 
     $state.go('settings'); 
    } 

}); 

如果我切換到沒有任何解決另一種狀態,我無法切換回主頁,按鈕只是d現在不做任何事情。

此外,而不是處理重新方向從homeCtrl設置,我將如何做到這一點的決心,那不是一種更好的方法

採用了棱角分明1.5.x版本和UI,路由器0.2 0.18

編輯:

我沒有使用的決心,而是

$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { 
      AuthService.getAccess().then(function (access) { 
       if (!access && toState.name !== "settings") { 
        event.preventDefault(); 
        toastr.warning('Your trial has expired'); 
        $state.go('settings'); 
       } 
      }); 
     }); 

但是我注意到的是,我的UI將在someti加載之前mes在authService.getAccess()之前完成,所以我遇到了競爭條件。

我搬到了解決,因爲這給了我在申請流程更好的控制。

回答

0

另一種方法是什麼你是 - 增加一個回調到每一個過渡的開始。

const app = angular.module('yourApplication'); 

app.run([ 
    '$state', '$transitions', 'authManager', 
    function ($state, $transitions, authManager) { 

     $transitions.onStart({from: ''}, function (transition) { 
      const to = transition.$to(); 
      const routeName = to.name; 

      if(!authManager.isAuthorizedRoute(routeName)) { 
       // here you can substitute login with any other state 
       // returning another target will break the transition and direct to another state 
       return transition.router.stateService.target('login'); 
      } 

      // if nothing is returned the transition will continue 
     } 
    } 

]); 

編輯:

由於getAccess執行異步 - 還有另一種解決方案:

1.創建一個父狀態,把解決有你的決心

$stateProvider.state('authorized', { 
    resolve: { 
     access: function(AuthService) { 
      return AuthService.getAccess(); 
     } 
    } 
}) 

2.Define你的狀態父狀態

.state('yourSTATE', { 
    ..... 
    parent:  'authorized', 
    .... 
}) 

的$轉變3.Handle的onSuccess(https://github.com/angular-ui/ui-router/issues/2946)來訪問解決數據,然後再決定是否轉型成功應該和重定向到另一個目標

app.run([ 
    '$transitions', 
    function ($transitions) { 

     $transitions.onSuccess({}, function(transition) { 
      var hasAccess = transition.getResolveValue('access'); 

      if(!hasAccess) { 
       return transition.router.stateService.target('login'); 
      } 
     }); 
    } 
]); 
+0

見我的編輯,我有過這樣的事情,但我想比賽競爭條件。所以我轉而解決,以確保在加載狀態之前完成getAccess()。 – Batman

+0

是的,因爲'getAccess'異步工作,在這種情況下不起作用。我會編輯一個解決方案 –

+0

@Batman,更新解決方案 - 請檢查它並讓我知道,無論它是否有幫助。 –