Ui-Router otherwise rule with ng-admin

107 views Asked by At

I have got a problem in an angular app, where I have integrated ng-admin to provide a simple admin panel. I have also integrated Authentication and want to point to a login state, when there is no current session.

Ng-admin itself sets ui-router's otherwise method to point directly to the dashboard. Even when setting my own $urlRouterProvider.otherwise(...) I am not able to force ui-router to use my otherwise function.

I tried it like this:

$urlRouterProvider.otherwise(function ($injector) {
    console.log('Hello World?!');
    state.go('login');
});

But the console.log is never printed...

I would like to intercept the state transition to the dashboard, before any dashboard-code is run, and redirect the user to the login page first.

Any hints and ideas are greatly appreciated.

1

There are 1 answers

0
René Jahn On

Thanks @user8175473 for pointing me into the right direction.

I have solved the problem using $on('$stateChangeStart) as $on('$stateChangeSuccess) is called after some state code is executed.

$rootScope.$on('$stateChangeStart', function(event, toState) {
    if(toState.name !== 'login' && !service.isLoggedIn()) {
        event.preventDefault();
        $state.go('login');
    }
});

Note that event.preventDefault() is needed to cancel the state transition completely.