3.5路由守卫
拥有权限才进入路由
常见的路由守卫如下:
CanActivate:进入路由前促发,当条件不满足时,无法进入该路由
CanDeactivate:从当前路由离开时促发,当条件不满足时,无法离开路由
Resolve:在路由激活之前获取路由数据
CanActivate CanActivate的值为一个数组,数组中可以添加多个路由守卫,只有当所有的路由守卫都通过时,才可以进入路由。
CanDeactivate CanActivate的值为一个数组,数组中可以添加多个路由守卫,只有当所有的路由守卫都通过时,才可以促发导航。
Resolve Resolve会在进入路由前促发,负责加载信息,当信息加载后再进入路由。如果加载不到想要的信息时,可以根据要求进行处理,如发出提示,或跳转其他路由。Resolve传递的值是一个对象,对象的属性为需要传递的参数,属性值为自定义的Resolve路由守卫。
自定义CanActivate路由守卫login.guard.ts
1.新建继承CanActivate接口的LoginGuard类,实现canActivate()方法。 2.在canActivate()方法中编写逻辑,当canActivate()方法返回为true时,允许进入路由,反之,当canActivate()方法返回为false时,不允许进入路由。
export class LoginGuard implements CanActivate {
canActivate(): boolean {
if (Math.random() > 0.5) {
console.log('用户已成功,正在导航');
return true;
} else {
console.log('用户未登录');
return false;
}
}
}
自定义CanDeactivate路由守卫unsave.guard.ts
1.新建继承CanDeactivate接口的UnSaveGuard类,实现canDeactivate()方法。CanDeactivate接口中需要指定一个泛型,该泛型为路由守卫保护的路由组件类型。 2.在canDeactivate()方法中编写逻辑,当canDeactivate()方法返回为true时,允许离开路由,反之,当canDeactivate()方法返回为false时,不允许离开路由。
export class UnSaveGuard implements CanDeactivate<ProductComponent> {
canDeactivate(component: ProductComponent): boolean {
return window.confirm('内容还未保存,确定离开吗?');
}
}
自定义Resolve路由守卫product.resolve.ts
1.新建继承Resolve接口的ProductResolve类,实现resolve()方法。Resolve接口中需要指定一个泛型,该泛型为路由守卫保护的路由组件类型。 2.在resolve()方法中编写逻辑,加载数据返回或跳转等其他操作。
@Injectable()
export class ProductResolve implements Resolve<Product> {
constructor(private router: Router) {
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Product> | Promise<Product> | Product {
const id = route.params['id'];
if (id === 1) {
return new Product(1, 'apple');
} else {
this.router.navigate(['/home']);
return undefined;
}
}
}
使用路由守卫
1.在路由模块中为路由守卫提供注册器
providers: [LoginGuard, UnSaveGuard]
2.在对应的路由上使用路由守卫
{path: 'chat', component: ChatComponent, canActivate: [LoginGuard], canDeactivate: [UnSaveGuard]}
{path: 'chat', component: ChatComponent, canActivate: [canActivate路由守卫], canDeactivate: [canDeactivate路由守卫]}
使用Resolve路由守卫
1.在路由模块中为路由守卫提供注册器
providers: [ProductResolve]
2.在对应的路由上使用路由守卫
{path: 'product/:id', component: ProductComponent, resolve: {
product: ProductResolve
}
}
{path: 'product/:id', component: ProductComponent, resolve: {
传递的参数名: 传递数值来源,其实就是自定义的Resolve路由守卫
}
}
3.接受resolve路由守卫中传递的值
this.routeInfo.data.subscribe((data: { product: Product }) => {
this.productId = data.product.id;
this.productName = data.product.name;
});
Last updated
Was this helpful?