0

What is the best way to check authentication status in angular 2? In angular 1, with .run method, it is straightforward the authentification token is in session/local storage, if the token is not present it means that the user is not connected, here is how I do it :

function authenticationCheck(HOME_PAGE, $http, $localStorage, $location, $rootScope, $sessionStorage) {
// keep user logged in after page refresh
if ($localStorage.token) {
  $http.defaults.headers.common.Authorization = $localStorage.jwt;
}

// redirect to login page if not logged in and trying to access a restricted page
$rootScope.$on('$locationChangeStart', function (event, next, current) {
  var publicPages = ['/login'];
  var restrictedPage = publicPages.indexOf($location.path()) === -1;
  if (restrictedPage && !($localStorage.jwt || $sessionStorage.jwt)) { // redirect to login
    $location.path('/login');
  }
  if (($localStorage.jwt || $sessionStorage.jwt) && $location.path() === '/login') { // redirect to home page if connected
    $location.path(HOME_PAGE);
  }
});
}

I would like to have the equivalent with angular 2, it seems that there are no more .run or .config methods.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Moussa
  • 4,066
  • 7
  • 32
  • 49

0 Answers0