0

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.

René Jahn
  • 1,155
  • 1
  • 10
  • 27
  • did you try to use $on("stateChangeSuccess") – hasan Jun 28 '17 at 21:52
  • As I am setting the routing states in the configuration phase of angular, I am not sure where to put this...? Can I use this in an `angular.run(...)` block? – René Jahn Jun 30 '17 at 07:44
  • You can use it in your main module controller – hasan Jun 30 '17 at 07:45
  • The "main" controller lies in ng-admin, I have only controllers for specific states, which are not executed on first load of the application. – René Jahn Jun 30 '17 at 07:54
  • Can you try to use resolve function for specific states then you would be able to check session and change states? – hasan Jun 30 '17 at 08:01
  • For my own states I could easily add resolve, but I'm not sure how to do this for states defined in another module – René Jahn Jun 30 '17 at 08:03
  • can you add your main module to make question more clear? – hasan Jun 30 '17 at 08:05
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/148026/discussion-between-user8175473-and-minato). – hasan Jun 30 '17 at 08:06

1 Answers1

0

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.

René Jahn
  • 1,155
  • 1
  • 10
  • 27