Подтвердить что ты не робот

AngularJS Как перенаправить на следующий маршрут после входа в систему

Используя $rootScope. $on ('$ routeChangeStart', function (event, next, current), я перенаправляюсь на страницу signin, если маршрут требует аутентификации. Это работает отлично.

Как перенаправить обратно к намеченному маршруту, хотя после входа?

4b9b3361

Ответ 1

Это упрощенная версия того, что работает для меня:

app = angular.module('ngApp', []).config(function ($routeProvider) {
  $routeProvider
    .when('/dashboard', {
        templateUrl: 'dashboard.html',
        controller: 'dashboardController',
        loginRequired: true //
      })
    .when('/login', {
        templateUrl: 'login.html',
        controller: 'loginController'
      })
    .otherwise({redirectTo: '/login'})
});

Затем в блоке запуска приложения:

app.run(function ($location, $rootScope) {
    var postLogInRoute;

    $rootScope.$on('$routeChangeStart', function (event, nextRoute, currentRoute) {

    //if login required and you're logged out, capture the current path
        if (nextRoute.loginRequired && Account.loggedOut()) {
          postLogInRoute = $location.path();
          $location.path('/login').replace();
        } else if (postLogInRoute && Account.loggedIn()) {
    //once logged in, redirect to the last route and reset it
          $location.path(postLogInRoute).replace();
          postLogInRoute = null;
        }
    });
});

Ответ 2

Вот пример того, как я это делаю, надеюсь, что это поможет:

В провайдере маршрутов сначала настройте общедоступный доступ:

// Just a demo on how the routes were set up to determine public access
angular.module('ngApp', []).config(function ($routeProvider) {

    $routeProvider

        .when('/', {
            templateUrl: 'views/main.html',
            controller : 'MainController',
        })

        .when('/login', {
            templateUrl  : 'views/login.html',
            controller   : 'LoginController',
            publicAccess : true // This is used in $routeChangeStart later
        });

    });

});

Тогда:

$rootScope.$on('$routeChangeStart', function(event, next, current) {

    var publicAccess = next.publicAccess || false;

    // This is just a service I made, this is how I check logged in status
    // AuthenticationService.check() returns a promise
    AuthenticationService.check().then(function() {

        // As this is a promise, this block signals that the user is logged in
        // If the page is marked as public access, then redirect to private area    
        if (publicAccess)
            $location.path('/').replace();

    }, function() {

        // Since this segment of the promise signals that the user is not
        // logged in, if the page is not publicly accessible, redirect to login
        if (!publicAccess)
            $location.path('/login').replace();

    });

});

Ответ 3

Следующий ответ от OP.


Вот как я его решил:

Я добавил это событие в строку $routeChangeStart

$rootScope.$on('$routeChangeStart', function(event, next, current) { 

  if (next.authRequired) {

    var deferred = $q.defer(),
          _token = mainConfig.csrfToken;

    security.getCurrentUser(true, _token).success(function (data, status, headers, config)     {

      if(status == 200) {
        // set the local scope variables
        next.scope.isAuthenticated = true;
        next.scope.user = security.currentUser;
        // Broadcast out to each of the listeners
        $rootScope.$broadcast('currentUserAuthenticated');

      // Any other response requires a signin.  Redirect.  
      } else {
        next.scope.isAuthenticated = false;
        next.scope.user = null;
        $rootScope.$broadcast('authenticationRequired', $location.url());
        $location.path('/signin');
      }
    });
  }
});

Затем в моей безопасности factory я прослушал событие и сохранил его, например:

$rootScope.$on('authenticationRequired', function(event, callingRoute) {
redirectRoute = callingRoute;
});