使用UI路由器登录后重定向到原始状态

cus*_*ice 4 angularjs angular-ui-router

使用UI路由器,当用户访问需要登录的页面时,在他们登录后,我想将它们重定向回他们来自的原始URL.

所以,例如,

/account/profile --> LOGIN PAGE (/login) --> /account/profile
/someother/requiredLogin/path --> LOGIN PAGE (/login) --> /someother/requiredLogin/path
Run Code Online (Sandbox Code Playgroud)

我的路线:

  $stateProvider
    .state('accountProfile', {
      url: '/account/profile',
      data: {
        requiresLogin: true
      },
      views: {
        '': {
          templateProvider: function($templateCache) {
            return $templateCache.get('templates/profile.html');
          }
        }
      },
    })
    .state('anotherPage', {
      url: '/someother/path',
      data: {
        requiresLogin: true
      },
      views: {
        '': {
          templateProvider: function($templateCache) {
            return $templateCache.get('templates/other.html');
          }
        }
      },
    })
Run Code Online (Sandbox Code Playgroud)

在我的应用程序的运行块中,我有:

.run(['$rootScope', '$state', 'LoginService',
    function($rootScope, $state, LoginService) {

      // Change title based on the `data` object in routes
      $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
        var requiresLogin = toState.data.requiresLogin;

        if (requiresLogin && !LoginService.check()) {
          event.preventDefault();
          $state.go('login');
        }

      });
    }
  ])
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我在requiresLogin为每条路线添加一个基本工作时,只是重定向到login路由.如何跟踪原始URL并在登录后将其重定向回原始URL?

dyl*_*ver 6

更新登录状态配置,以包含要在登录时重定向到的状态名称的默认参数(toState)以及使用原始状态更改(toParams)传递的任何参数.如果您没有定义默认值,那么当您在登录控制器中检查它们时,$ state.params将始终为空 - 即使您提供了$ stateChangeStart处理程序的值!

  .state('login', {
    data: {'requiresLogin': false},
    params: { 
      'toState': 'profile', // default state to proceed to after login
      'toParams': {}
    },
    url: 'login',
  })
Run Code Online (Sandbox Code Playgroud)

修改您的运行块以捕获并传递请求的(未授权)状态:

    $state.go('login', {'toState': toState.name, 'toParams': toParams});
Run Code Online (Sandbox Code Playgroud)

在登录控制器成功处理程序中,以下内容将使您进入$ stateChangeStart中指定的状态或状态配置中声明的默认状态:

      $state.go($state.params.toState, $state.params.toParams);
Run Code Online (Sandbox Code Playgroud)