1. CanActivate 路由进入
新建守卫focusGuard.ts文件
import { CanActivate } from '@angular/router';
export class LoginGuard implements CanActivate {
canActivate () {
let loggedIn: boolean = Math.random() < 0.5;
console.log(loggedIn)
return loggedIn // retunrn出true或false true允许进入路由 false不允许进入路由
}
}
配置route.ts文件
import { RouterguardComponent } from './routerguard/routerguard.component';
import { LeaveGuard } from './routerguard/unfocusGuard'; // 这里!!!!!!
const routes: Routes = [
...
{path:'routerguard',component:RouterguardComponent,
canActivate:[LoginGuard], // 这里!!!!!!!!
},
]
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule],
providers: [LoginGuard] // 这里!!!!!!!
})
这时当要进入routerguard路由时 会先判断守卫focusGuard.ts中return出去的值 true允许进入路由 false不允许进入路由
2. CanDeactivate 路由离开
新建守卫unfocusGuard.ts文件
import { CanDeactivate } from '@angular/router';
import { RouterguardComponent } from './routerguard.component';
export class LeaveGuard implements CanDeactivate<RouterguardComponent> {
canDeactivate (component: RouterguardComponent) {
let loggedIn: boolean = Math.random() < 0.5;
console.log(component) // componrnt为 routerguard.component的内容 可获得其变量
// return window.confirm("确定要离开吗");
return loggedIn
}
}
配置route.ts文件
import { RouterguardComponent } from './routerguard/routerguard.component';
import { LeaveGuard } from './routerguard/unfocusGuard'; // 这里!!!!!!!!!
const routes: Routes = [
...
{path:'routerguard',component:RouterguardComponent,
canDeactivate:[LeaveGuard] // 这里!!!!!!!!!
},
]
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule],
providers: [LeaveGuard] // 这里!!!!!!!!!!
})
这时当要从routerguard路由离开时 会先判断守卫unfocusGuard.ts中return出去的值 true允许离开路由 false不允许离开路由