Ionic 2 Route Guards?

Just recently I created a little tutorial on using Auth Guards!

Right now with Ionic 3.1 I think there might be a small glitch, so while in the tutorial we can catch whether we are allowed to enter a page inside the .catch() block, the result currently only comes to a .then() block!

1 Like

this tuto is really far from Route gards. not revealant at all.

@luchillo17 you can try a slimmer and more elegant approach using the TypeScript decorators.

You must create a decorator to use in a class, this decorator can implement the authentication check on the ionViewWillEnter method, as you wanted. Then you can use this decorator in your page class that should be protected, like this:

@AuthGuard()
@IonicPage()
@Component({
    selector: 'page-start',
    templateUrl: 'start.html',
})
export class StartPage {}

Where @AuthGuard() is the decorator created to do this user verification.
You could also implement parameters in your decorator, for example, to verify that the user also has permission to access a certain page, this in case your app has several levels of access per user.
So in addition to the decorator check if the user is logged in, it also checks if the user has access to the resource:

@AuthGuard('shows, comments, episodes')
@IonicPage()
@Component({
    selector: 'page-start',
    templateUrl: 'start.html',
})
export class StartPage {}
1 Like