1.在app的shared目录下新建login-guard文件夹在其新建login-guard.ts文件
import { CanActivate, CanActivateChild } from '@angular/router';
import { Observable } from 'rxjs';
import { Injector, Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { StartupService } from '@core/startup/startup.service';
@Injectable()
export class LoginGuard implements CanActivate, CanActivateChild {
constructor(
private router: Router,
private injector: Injector,
public st: StartupService,
) { }
canActivate(): Observable<boolean> | Promise<boolean> | boolean {
return this.logIn();
}
canActivateChild(): Observable<boolean> | Promise<boolean> | boolean {
return this.logIn();
}
private logIn() {
let token = sessionStorage.getItem('token');
if (!token) {
this.goTo('/passport/login');
return false;
} else {
return true;
}
}
private goTo(url: string) {
setTimeout(() => this.injector.get(Router).navigateByUrl(url));
}
}
2.打开app.module.ts在providers里面添加模块
import { LoginGuard } from '@shared/login-guard/login-guard.module';
providers: [
LoginGuard
],
3.打开在app下的routes目录下的routes-routing.module.ts文件新增LoginGuard 路由拦截去掉ng-alain默认的路由拦截
import {LoginGuard } from '@shared/login-guard/login-guard.module';
const routes: Routes = [
path: '',
component: LayoutDefaultComponent,
// canActivate: [SimpleGuard],
canActivate: [LoginGuard],
children: [
]
]
网友评论