Ui-router - $ state.go () not working

Here is the app.js of my project:

(function () { 'use strict'; angular .module('app', ['ui.router', 'ngCookies', 'angular-inview', 'ngMaterial']) .config(config) .run(run); config.$inject = ['$stateProvider', '$urlRouterProvider', '$mdThemingProvider']; function config($stateProvider, $urlRouterProvider, $mdThemingProvider) { $mdThemingProvider.theme('default') .primaryPalette('deep-orange') .accentPalette('teal', { 'default': 'A400' }); $urlRouterProvider.otherwise('/app'); $stateProvider .state('app', { url: '/app', data: { clearenceLevel: 1 }, views: { '': { templateUrl: 'app/views/navbar.html', } } }) .state('home.works', { url: '/works', templateUrl: 'app/views/works.html', controller: 'WorksController as vm' }) .state('login', { url: '/login', templateUrl: 'app/views/login.html', controller: 'LoginController as vm', data: { clearenceLevel: 0 } }) .state('register', { url: '/register', templateUrl: 'app/views/register.html', controller: 'RegisterController as vm', data: { clearenceLevel: 0 } }); } run.$inject = ['$rootScope', '$location', '$state', '$cookieStore', '$http', 'AuthenticationService']; function run($rootScope, $location, $state, $cookieStore, $http, AuthenticationService) { $rootScope.globals = $cookieStore.get('globals') || {}; if ($rootScope.globals.currentUser) { $http.defaults.headers.common['aimm-token'] = $rootScope.globals.currentUser.token; $http.defaults.headers.common['aimm-id'] = $rootScope.globals.currentUser.id; } $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { var clearenceLevel = toState.data.clearenceLevel; var loggedIn = $rootScope.globals.currentUser; if (clearenceLevel > 0 && !loggedIn) { alert("redirecting"); return $state.go('login'); } }); } })(); 

$ State.go () simply cannot work for me. $on('$stateChangeStart'...); works fine, and a warning appears when you try to reach a protected state without a session. But return $state.go('login'); does not work. It redirects to /app .

Thank you for your help.

+5
javascript angularjs angular-ui-router
source share
2 answers

Well, thanks to @ Vanojx1, I found out that e.preventDefault(); been added e.preventDefault(); before $state.go('login'); earned. However, I do not understand why.

+10
source share

You need to execute $state.go in the main scope and not in the service (angular) or the virtual scope created temporarily.

You can also solve the problem by wrapping it in $timeout or setTimeout , which will register it in the browser loop that will be executed after the current method starts, etc., even with 0 milliseconds it will, for example.

 $timeout(()=>{$state.go('xyz')},0) 

or

 setTimeout(()=>{$state.go('xyz')},0); 
+5
source share

All Articles