You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS ui-router中$state.go跳转失效,登录拦截异常求助

Hey, let's break down what's going on here and fix it step by step.

First, the core issue with your current code is that it only runs once when the app initializes. When you directly type an authorized route like app.dashboard-v1 into the browser, here's the messy sequence of events:

  1. The app loads, runs your initialization code, sees no token, and tries to jump to access.signin.
  2. But the browser has already started loading the app.dashboard-v1 route you entered. Since your initialization code's $state.go doesn't block the original route navigation, the router ends up prioritizing the target route after the failed login redirect attempt.

Plus, you have a tiny syntax error in your code: $state.go('access.signin) is missing a closing single quote (should be $state.go('access.signin')), which might be causing unexpected behavior too.

To fix this properly, you need to globally intercept every route change to check if the user is authorized before letting them access protected routes. Here's how to do it with ui-router (since you're using $state):

Solution 1: Using $stateChangeStart (for older ui-router versions)

Add this to your app's run block to listen for every route transition:

angular.module('yourAppName').run(['$rootScope', '$state', '$localStorage', function($rootScope, $state, $localStorage) {
  // Listen for when a state change is about to happen
  $rootScope.$on('$stateChangeStart', function(event, toState) {
    // Define which states require authentication (e.g., all starting with 'app.')
    const requiresAuth = toState.name.startsWith('app.');
    // Check if user is logged in (use optional chaining to avoid errors if $localStorage.globals is undefined)
    const isLoggedIn = !!$localStorage.globals?.access_token;

    if (requiresAuth && !isLoggedIn) {
      event.preventDefault(); // Block the original route change
      $state.go('access.signin'); // Redirect to login page
    }
  });

  // Your fixed initialization code
  if ($localStorage.globals?.access_token) { 
    $rootScope.globals = $localStorage.globals; 
    // Only redirect to dashboard if we're not already on a protected route
    if (!$state.current.name.startsWith('app.')) {
      $state.go('app.dashboard-v1'); 
    }
  } else {
    // Only redirect to login if we're not already there
    if ($state.current.name !== 'access.signin') {
      $state.go('access.signin'); 
    }
  }
}]);

Solution 2: Using $transitions (for ui-router 1.x / AngularJS 1.6+)

If you're using a newer version of ui-router, $stateChangeStart is deprecated. Use $transitions instead:

angular.module('yourAppName').run(['$transitions', '$state', '$localStorage', function($transitions, $state, $localStorage) {
  // Intercept all transitions
  $transitions.onStart({}, function(transition) {
    const toState = transition.to();
    const requiresAuth = toState.name.startsWith('app.');
    const isLoggedIn = !!$localStorage.globals?.access_token;

    if (requiresAuth && !isLoggedIn) {
      // Return the login state to redirect and block the original transition
      return $state.target('access.signin');
    }
  });

  // Fixed initialization code (same as above)
  if ($localStorage.globals?.access_token) { 
    $rootScope.globals = $localStorage.globals; 
    if (!$state.current.name.startsWith('app.')) {
      $state.go('app.dashboard-v1'); 
    }
  } else {
    if ($state.current.name !== 'access.signin') {
      $state.go('access.signin'); 
    }
  }
}]);

Why this works:

  • The route interception runs every time a state change is attempted, whether the user clicks a link, refreshes the page, or types the URL directly.
  • event.preventDefault() (or returning the login state in $transitions) ensures the protected route never loads if the user isn't logged in.
  • We added checks to avoid unnecessary redirects (e.g., if the user is already on the login page or a protected route).

Don't forget to fix that missing single quote in your original code—it's easy to miss but can cause weird bugs!

内容的提问来源于stack exchange,提问作者Vishnu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:21:43