Skip to content Skip to sidebar Skip to footer

Conditionally Navigate To State With Angular Ui-router

Currently, we have a 'Portfolio' tool in beta. Once a user logs in to the main app, if they have been given access to the beta, they can navigate to the Portfolio tool directly, wi

Solution 1:

I ran in the same problem days ago. Instead of using resolve, I check if the user is logged when state changes, defining run module and listening $stateChangeStart event, then check if the current state required authentication. If so, check if the user is logged in.

angular.module('portfolio.manager').config(function ($logProvider, $stateProvider) {
'use strict';

    $stateProvider
    .state('portfolio.manager', {
        url: '/manager',
        resolve: {
            portfolioAuthService: 'portfolioAuthService',

            User: function(portfolioAuthService){
              return portfolioAuthService.getUser();

            },
            Portfolios: function (User, portfolioManagerService) {
                return portfolioManagerService.getPortfolios();
            }
        },
        data: {
            requiredAuthentication: true
        },
        views: {
            'main@': {
                templateUrl: 'app/portfolio/manager/portfolio-manager.html',
                controller: 'PortfolioManagerCtrl'
            },
            'no-portfolios@portfolio.manager': {
                templateUrl: 'app/portfolio/manager/partials/no-portfolios.html'
            },
            'create@portfolio.manager': {
                templateUrl: 'app/portfolio/manager/partials/create.html'
            }
        }
    })

})
.run(run);

  run.$inject = ['$rootScope','$state','loggedIn'];

  function run($rootScope,$state,loggedIn){

    $rootScope.$on('$stateChangeStart',function(e,toState){

      if ( !(toState.data) ) return;
      if ( !(toState.data.requiredAuthentication) ) return;

      var _requiredAuthentication = toState.data.requiredAuthentication;


      if (_requiredAuthentication && !loggedIn.checkUser() ){

        e.preventDefault();
        $state.go('portfolio.login', { notify: false });
        console.log('not authorized');
      }
      return;


    });
  };

Post a Comment for "Conditionally Navigate To State With Angular Ui-router"