0

I am storing a token in localStorage after authentication, but i need to delete it and redirect to some router each time i do a refresh.

I have no ideea how to do it in angular. I am using a very hacky way using plain js.

window.addEventListener('load', function (e) {
  if (window.sessionStorage !== null && (window.location.href.indexOf('/signin') === -1 &&  window.location.href.indexOf('confirm-user') === -1)) {
    window.sessionStorage.clear();
    window.location.href = '/signin';
  }
});

I was thinking of adding an authentication guard, but i'm sure there should be a more angular way of doing this.

  • 2
    If you have a value that you don’t want to survive a page reload (assuming that’s what you mean by “doing a refresh”) - then why do you put it into localstorage in the first place …? A plain old normal JavaScript _variable_ would achieve that without you having to perform any extra steps ... – CBroe Jun 08 '17 at 08:46

1 Answers1

0

I would suggest to create some auth service to store your token as a plain variable and a Guard to prevent redirects to secured pages without token. You can implement it in one service:

@Injectable()
export class AuthService implements CanActivate, CanActivateChild {
    token:String;
    canActivateChild = this.canActivate;
    constructor(private router: Router) {}
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (!this.token) {
            this.router.navigate(['/signin']);
            return false;
        }
        return true;
    }
}

export const ROUTES: Routes = [{
    path: 'signup',
    component: SignupComponent
}, {
    path: 'securedpath',
    component: SecuredComponent,
    canActivateChild: [AuthService],
    canActivate: [AuthService]
}]

But this service should be singleton. Keep it in mind. Declare it in providers list of your app.module (or core.module if your using Jonh Papa's styleguide)