我的路线是: -
const appRoutes: Routes = [
{ path: 'alert/:id', component: AlertDetailComponent },
{ path: 'alerts', component: AlertsComponent },
{ path: 'dashboard', component: EriskDashboardComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'logout', component: LogoutComponent },
];
我希望如果本地存储包含token_id
,那么./login会重定向到EriskDashboardComponent
答案 0 :(得分:3)
在'login'
路线中添加CanActivate后卫:
{ path: 'login', component: LoginComponent, canActivate: [CheckToken] }
在守卫内部(在我的示例中名为CheckToken
),检查localStorage并重定向用户:
// check-token.service.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable()
export class CheckToken implements CanActivate {
constructor(private router: Router) {
canActivate() {
const myToken = ...; // check localStorage
if (myToken) {
this.router.navigate(['/dashboard']);
}
}
}