-
Notifications
You must be signed in to change notification settings - Fork 22
Angular路由守卫 canActivate
L edited this page Apr 4, 2019
·
5 revisions
canActivate
控制是否允许进入路由。
canActivateChild
等同 canActivate,只不过针对是所有子路由。
创建路由守卫
import { Injectable } from '@angular/core';
import {
CanActivate,
Router,
ActivatedRouteSnapshot,
RouterStateSnapshot,
CanActivateChild,
} from '@angular/router';
@Injectable()
export class CanActivateGuard implements CanActivate, CanActivateChild {
constructor(
private _router: Router,
) { }
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
): boolean {
//在这里判定是否跳转目标路由
//如果可以跳转页面,返回true,不能,则返回false
//建议逻辑
//1.是否登录
//2.访问是否要求权限
//3.查询当前登录用户是否拥有目标权限
//如果不符合条件,则根据selectBestRoute()方法返回其他页面
//这里的permission是在routes-routing.module.ts中data:{permission:'yourPermission'}传参过来的内容
console.log('该页面所需权限:'+route.data['permission']);
return true;
}
canActivateChild(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
): boolean {
return this.canActivate(route, state);
}
}
设置路由守卫
{
path: 'can-activate',
component: CanActivateComponent,
//权限permission,CanActivateGuard判定
data:{permission:'yourPermission',title: '你的标题'},
//设置路由守卫为CanActivateGuard
canActivate: [CanActivateGuard],
}