Redirection after logging in using a UI router

Using a UI router, when a user goes to a page that requires a login, after logging in I would like to redirect them back to the original URL from which they came.

So for example

/account/profile --> LOGIN PAGE (/login) --> /account/profile
/someother/requiredLogin/path --> LOGIN PAGE (/login) --> /someother/requiredLogin/path

My routes:

  $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');
          }
        }
      },
    })

In my application launch block, I have:

.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');
        }

      });
    }
  ])

As you can see, I am doing the basic work of adding requiresLoginto each route, which simply redirects always to the route login. How can I track the source url and redirect it back after login?

+4
source share
1 answer

, (toState), , (toParams). , $state.params , - $stateChangeStart!

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

, () :

    $state.go('login', {'toState': toState.name, 'toParams': toParams});

, $stateChangeStart, , :

      $state.go($state.params.toState, $state.params.toParams);
+6

Source: https://habr.com/ru/post/1589080/


All Articles