Search code examples
angularjsauthenticationngcomponentrouterangular-component-router

Angular 1.5 $routerOnActivate on Root Router


I want to make sure that the user is logged in properly before proceeding to any of the components he/she's trying to reach, if they're not logged in. Send them to login.

My idea is to do a check in the $routerOnActivate in the root router. Which to me would solve the issue for any sub routes.

However nothing seems to happen if i just try to log something. Example:

angular
    .module('app')
    .config(function($locationProvider) {
        $locationProvider.html5Mode(true);
    })
    .value('$routerRootComponent', 'app')
    .component('app', {
          templateUrl:'landing.html',
          controller: MainController,
          $routeConfig: [
                { path: '/', name: 'Dashboard', component: 'dashboard', useAsDefault: true },
                { path: '/media', name: 'Media', component: 'media'}
                ...
          ]
    });


function MainController(){
    this.$routerOnActivate = function(next, previous){
        console.log('activated', next, previous);
    };
}

The same code this.$routerOnActivate works if i put it in any of the Components which are specified in the routeConfig. However obviously I don't want to make the same check in every component, but rather solve it once globally.

What is the approach for 1.5?


Solution

  • Paste from my comment as requested

    What about perform your check on the loading on the page ? This would run perfectly in an angular.run.

    And if you want to handle session expiration, you can add an interceptor to all requests and watch for a 401 response.