Reputation: 855
I have an Angular application using basic Routing module. The below shows my defined routes:
...
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent }
];
...
Now I want to protect my dashboard route. I want to route only when I have a localStorage
object named token
. How can I do it?
var local = JSON.parse(localStorage.getItem('token'));
Something like:
...
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', checkLogin, component: DashboardComponent }
];
...
function checkLogin(){
// do the logic
}
Upvotes: 0
Views: 2070
Reputation: 3315
You should use Angular Route Guards. Like this:
import { CanActivate } from '@angular/router';
class DashBoardGuard implements CanActivate {
canActivate() {
if (// your condition) {
return true; // all fine
} else {//maybe redirect somwhere}
}
}
// in your routes
...
{path: 'dashboard', canActivate: {[DashBoardGuard]}
Read more about guards here
Upvotes: 1
Reputation: 2831
You can do that with a route guard that implements the CanActivate interface: https://angular.io/api/router/CanActivate
The canActivate method can return a boolean if it's supposed to be checked synchronously or promise/observable if it's async. Anyway, in your case, you're just checking the localStorage so you simply return true or false based on the token.
Upvotes: 1