1、在路由中进行配置,当token失效时不允许再跳转到模块
1)编写LoginGuard 服务
import { CanActivate, CanActivateChild } from '@angular/router';
import { Observable } from 'rxjs';
import { Inject, Injector, Injectable } from '@angular/core';
import { TokenService, DA_SERVICE_TOKEN } from '@delon/auth';
import { AppUtil } from '@core/util/util.service';
import { Router } from '@angular/router';
import { StartupService } from '@core/startup/startup.service';
@Injectable()
export class LoginGuard implements CanActivate, CanActivateChild {
constructor(
@Inject(DA_SERVICE_TOKEN) private tokenService: TokenService,
private util: AppUtil,
private router: Router,
private injector: Injector,
public st: StartupService,
) {}
canActivate(): Observable | Promise | boolean {
return this.logIn();
}
canActivateChild(): Observable | Promise | boolean {
return this.logIn();
}
private logIn() {
const token = this.tokenService.get();
// const autoLogin = this.util.getAutoLogin(); // 缓存此处不需要判断,token失效就强制退出了
// 处理token失效 不允许进行路由跳转,强制跳转到登录页面
if (!token || this.util.isEmptyObject(token) || !this.st.firstLoad) {
this.goTo('/passport/login');
return false;
} else {
return true;
}
}
private goTo(url: string) {
setTimeout(() => this.injector.get(Router).navigateByUrl(url));
}
}
2)在路由中进行配置
const routes: Routes = [
{
path: '',
component: LayoutDefaultComponent,
children: [
{
path: '',
redirectTo: 'dashboard/v1',
pathMatch: 'full',
canActivate: [LoginGuard],
},
{
path: 'dashboard',
redirectTo: 'dashboard/v1',
pathMatch: 'full',
canActivate: [LoginGuard],
},
{
path: 'dashboard/v1',
component: DashboardV1Component,
canActivate: [LoginGuard],
},
{
path: 'soc',
loadChildren: './soc/soc.module#SocModule',
canActivate: [LoginGuard],
},
],
canActivateChild: [ LoginGuard ],
},
{
path: 'passport',
component: LayoutPassportComponent,
children: [
{
path: 'login',
component: UserLoginComponent,
data: { title: '登录', titleI18n: 'pro-login' },
},
],
},
// 单页不包裹Layout
{ path: 'callback/:type', component: CallbackComponent },
{
path: 'lock',
component: UserLockComponent,
data: { title: '锁屏', titleI18n: 'lock' },
},
{ path: '403', component: Exception403Component },
{ path: '404', component: Exception404Component },
{ path: '500', component: Exception500Component },
{ path: '**', redirectTo: 'dashboard', canActivate: [LoginGuard]},
];
2、编辑自动登录本地缓存的存取
public getAutoLogin() {
const autoLogin = localStorage.getItem('autoLogin');
if (autoLogin === 'true') {
return true;
} else {
return false;
}
}
public setAutoLogin(val) {
localStorage.setItem('autoLogin', val);
}