Trying to redirect a user when they enforce to go to a link like /dashboard, it should check the localStorage if its empty go back to home basically.
Can't seems to do var checkStorage without being in a function, I would do a function but not sure how to initiate it automatically.
Guessing to initialize a function is ngOnInit, similar to init () {} in angular 1?
export class DashboardComponent {
constructor(private router: Router) {}
var checkStorage = localStorage.getItem('username');
if(checkStorage = null) {
this.router.navigate(['/']);
}
logoutAction (){
if(localStorage.getItem('username') != null){
localStorage.removeItem('username');
this.router.navigate(['/']);
}
}
}
Answer I found, but if there's a better way please share.
ngOnInit () {
this.checkStorage();
}
checkStorage() {
var checkStorage = localStorage.getItem('username');
if(!checkStorage) {
this.router.navigate(['']);
}
}