nCore
nCore

Reputation: 2087

angular 2 check localStorage to redirect

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(['']);
        }
    }

Upvotes: 3

Views: 2589

Answers (1)

Juanjo Salvador
Juanjo Salvador

Reputation: 1093

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!

Upvotes: 1

Related Questions