0

I have declared $rootScope.$on function under the myApp.run to check token value in every authenticated page.but its not working.I do not understand why its not working.Please help me.

app.js

myApp.run(['$rootScope','$state', '$location', 'loginService', function ($rootScope,$state, $location, loginService) {

    console.log(" under run => ");
    $rootScope.$on('routeChangeStart', function (event, next, current) {
        /*If route is authenticated then check if the user has access token, else return to login screen*/

        console.log(event);

        if (next.$$route.authenticated) {

            var userAuth = loginService.getUserToken();
            console.log(" usertoken => " +userAuth);
            if (!userAuth) {
                $location.path("/");
            }
        }

    });
 }]);

code print on console "under run =>" but it is not printing event object and also not check if condition.

2 Answers2

2

Be care of the $:

$rootScope.$on('$stateChangeStart',...)
Yin Gang
  • 1,443
  • 1
  • 10
  • 15
0
angular.module('...')..config( ['$routeProvider', function($routeProvider) {...}] )..run( function($rootScope, $location) {
// register listener to watch route changes
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  if ( $rootScope.loggedUser == null ) {
    // no logged user, we should be going to #login
    if ( next.templateUrl == "partials/login.html" ) {
      // already going to #login, no redirect needed
    } else {
      // not going to #login, we should redirect now
      $location.path( "/login" );
    }
  }         
});

The one thing that seems odd is that I had to test the partial name (login.html) because the "next" Route object did not have a url or something else. Maybe there's a better way?