Angular ui-router: how to delay drawing a template until authorization is complete?

My ui-router configuration is as follows:

$stateProvider .state('app', { url: '/app', abstract: true, templateUrl: 'sidemenu/sidemenu.html', controller: 'SideMenuCtrl' }) .state('login', { url: '/login', templateUrl: 'login/login.html', controller: 'LoginCtrl' }) .state('app.dashboard', { url: '/dashboard', views: { menuContent: { templateUrl: 'dashboard/dashboard.html', controller: 'DashboardCtrl' } } }) [More states here] $urlRouterProvider.otherwise('/app/dashboard'); 

When the user goes to /app/dashboard , I would like to check if they are allowed, and then:

  • redirect to /login if they are not authorized, or
  • allow you to see the control panel if they are authorized

This looks like a trick: (based on this example )

 $rootScope.$on('$stateChangeSuccess', function(event) { var path = $location.path(); if (path === '/login') { return; } // Halt state change from even starting event.preventDefault(); Auth.getCurrentUser().then(function(currentUser) { if (currentUser === null) { $state.go('login'); } else { // Continue with the update and state transition $urlRouter.sync(); } }); }); 

The only problem with this solution is that if an unauthorized user navigates to the control panel, the toolbar template is visible first . Only when the authorization response is returned does it change to the login template.

Is there a way to not show the control panel while we authorize the user?

I also tried changing $stateChangeSuccess to $stateChangeStart , but it really didn't work (routing seems completely broken then).

+6
source share
2 answers

How to use permission block?

 .state('app.dashboard', { url: '/dashboard', views: { menuContent: { templateUrl: 'dashboard/dashboard.html', controller: 'DashboardCtrl', resolve: { login: function($q, Auth) { var deferred = $q.defer(); Auth.getCurrentUser().then(function(currentUser) { if (currentUser == null) { deferred.reject(); } else { deferred.resolve(); } }); return deferred.promise; } } } } }) 

State changes will not be made until the promise is resolved, so the template should not be displayed. Rejecting a promise will raise $stateChangeError in accordance with this answer , so you will need to handle this error and redirect to the login page.

+8
source

You can use the solution on your routes and reject the promise when the user does not log in, so the controller will never be reached.

0
source

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


All Articles