简体   繁体   中英

Proper way to pause routing in angular

I have an angular application with guest functionality. It means what i create a guest account for all unauthorized users in background. And i need to pause routing till guest account will be created and i can specify auth token to all other request. At the moment i'm doing it by adding of resolve param to all routes.

.config(function ($routeProvider) {
    var originalWhen = $routeProvider.when;

    $routeProvider.when = function (path, route) {
        if (path && path.indexOf('sign') === -1) {
            route.resolve = route.resolve || {};
            route.resolve.userSync = ['User', function (User) {
                return User.isSynchronized.promise;
            }];
        }

        return originalWhen.call(this, path, route);
    };
});

But it looks like not very nice solution. Can anyone give me advice how do it by the proper way?

You can listen to rootScope locationChangeStart event

.run(['$rootScope', 'User', function ($rootScope, User) {
  $rootScope.userLoggedIn = false;

  var preventLocationChangeUnregister = $rootScope.$on('$locationChangeStart', function (event, newUrl, oldUrl) {
    if ($rootScope.userLoggedIn === false && newUrl.indexOf('sign') === -1) {
      event.preventDefault(); // This prevents the navigation from happening
    }
  });
  User.isSynchronized.promise.then(function () {
    preventLocationChangeUnregister(); //By calling this your event listener for the $locationChangeStart event will be unsubscribed
    //$rootScope.userLoggedIn = true; //Or you can set userLoggedIn to true without unregistering event
  });
}])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM