如果用户使用书签或手动输入 URL 直接访问某些路由,则尝试停止访问它们。路线是一组按特定顺序排列的链式路线。例如,像一个巫师。
在过去,我在使用 canActivate
和使用服务时没有任何问题,如果它没有正确的数据表明访问了以前的路由状态(即之前的第 1 页)第 2 页等)它会将用户路由到初始路由(第 1 页),但是在使用 enableTracing
并在几个快速生成的组件上测试它之后,似乎应用程序正在加载并访问 code>CanActivate
阻止访问路由的守卫,调用 this.router.navigate(['/example/route/path']);
似乎没有成功如果直接访问第 2 页或更多页,则它的目的地(第 1 页)。
在 AppRoutingModule
中放置一个未延迟加载的 TestComponent
或使用顶级 not-found
路由是可行的,但绝对MainModule
中没有任何内容是可路由的。所以它似乎与包含延迟加载模块的延迟加载模块有潜在关系。
有人找到解决这个问题的方法吗?或者这只是另一个与 Angular 中的延迟加载相关的问题,例如 entryComponents
- https://stackoverflow.com/a/51689994/1148107 .
我不确定为什么应用程序是这样设置的,所以最坏的情况我会尝试插入快速重构并扁平化功能模块的延迟加载。
可以激活
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this.storeService.hasAccess) {
return true;
}
this.router.navigate(['/store/page/1']); // Doesn't route to page 1
return false;
}
AppRoutingModule 路由
const routes: Routes = [
{
path: '',
loadChildren: './main/main.module#MainModule',
canActivate: [AuthGuard]
},
// ...
{
path: 'not-found',
loadChildren: './not-found/not-found.module#NotFoundModule'
},
{
path: '**',
redirectTo: 'not-found'
}
];
MainRoutingModule 路由
const routes: Routes = [
{
path: '', component: MainComponent,
children: [
{
path: '',
redirectTo: 'store',
pathMatch: 'full'
},
{
path: 'store',
loadChildren: './store/store.module#StoreModule'
},
// ...
]
}
];
StoreRoutingModule
const routes: Routes = [
{
path: '',
children: [
{
path: 'page/1',
component: Page1Component,
data: {
title: 'Store'
}
},
{
path: 'page/2',
component: Page2Component,
// Redirects to a blank page instead of page 1 when directly
// accessed by a browser bookmark
canActivate: [CanActivateStoreGuard],
data: {
title: 'Store'
}
},
// ...
]
}
];
最佳答案
您需要在 Angular 路由器订阅的可观察对象中执行路由更改。
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return new Observable((subscriber) => {
if (this.storeService.hasAccess) {
subscriber.next(true);
} else {
this.router.navigate(['/store/page/1']);
subscriber.next(false);
}
subscriber.complete();
});
}
我无法验证这是否能解决您的问题,但我记得遇到过这个问题。当我看着我的守卫时,这就是我所做的。
更新:
如果以上方法不起作用(我有疑问),那么您可以尝试将路由更改包装在 setTimeout
中。
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this.storeService.hasAccess) {
return true;
}
window.setTimeout(()=> this.router.navigate(['/store/page/1']));
return false;
}
关于由于延迟加载模块,无法在手动输入 URL 时从 CanActivate Guard 进行 Angular 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51886961/