3

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(['']);
        }
    }
nCore
  • 2,027
  • 7
  • 29
  • 57

1 Answers1

1

If you want block access until you are logged in, the Angular way says:

Let the backend works for us.

I'm not sure what backend are you using for this, but I remember when I was a PHP developer, we have a function in CodeIgniter Framework that redirects when there is no cookie.

If you want to restrict this using Angular 2 (not for production yet, remember!), your code seems good, but I found a mistake:

var checkStorage = localStorage.getItem('username');
if(checkStorage == null) {
    this.router.navigate(['/']);
}

Use the double equal to compare.

And if you want to execute it on init, I guess this can help you.

Converting Angular 1 to Angular 2 ngInit function

Good luck and happy coding!

Community
  • 1
  • 1
Juanjo Salvador
  • 1,073
  • 1
  • 12
  • 33
  • not using any backend yet, just all dummy. I will be setting a cookie but just playing with localStorage atm. I managed to check localStorage if I wrap that code in a function, so I tried ngOnInit() which works fine. But if someone else know the correct way then please share. – nCore Jul 07 '16 at 11:10
  • If it works, it is the correct way. Angular has a lot of style guides that defines "the correct way", just choose your favourite. Todd Motto is a good start point. – Juanjo Salvador Jul 07 '16 at 11:11
  • Check my original post, I edited it and include my answer using ngOnInit. Yeah I know if it works, it works but trying to find a better/efficient way of doing it. Will check Todd Motto. – nCore Jul 07 '16 at 11:13