Why does AngularJS with ui-router keep firing the $stateChangeStart event?

后端 未结 6 1613
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 18:29

I\'m trying to block all ui-router state changes until I\'ve authenticated the user:

$rootScope.$on(\'$stateChangeStart\', function (event, next, toParams) {         


        
6条回答
  •  旧时难觅i
    2020-12-04 19:12

    Try changing your run block to this:

        app.run([
                 '$rootScope', '$log','$state','$interval',
        function ($rootScope,   $log,  $state,  $interval) {
          var authenticated = false;
          $rootScope.$on('$stateChangeStart', function (event, next, toParams) {
            if (!authenticated) {
              event.preventDefault()
              //following $timeout is emulating a backend $http.get('/auth/') request
            }
          })
    
    
          var intervalCanceller = $interval(function() {
            //backend call
            if(call succeeds & user authenticated) {
              authenticated = true;
              $interval.cancel(intervalCanceller);
              $state.go(next, toParams);
            }
          }, 3000);
        }
      ])
    

提交回复
热议问题