要阻止父路由加载,可以在子路由的守卫中返回一个布尔值来控制是否可以继续加载父路由。以下是一个示例代码:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable()
export class ChildRouteGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree {
// 在这里添加你的逻辑来决定是否阻止父路由加载
const shouldBlockParentRoute = true;
if (shouldBlockParentRoute) {
// 阻止父路由加载并导航到其他页面
this.router.navigate(['/other-page']);
return false;
}
return true;
}
}
然后,在子路由的路由配置中使用该守卫:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ChildRouteGuard } from './child-route.guard';
const routes: Routes = [
{
path: 'parent',
canActivate: [ChildRouteGuard],
children: [
// 子路由配置
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ParentRoutingModule { }
在上述示例中,如果shouldBlockParentRoute
变量的值为true
,则阻止父路由加载并导航到其他页面(例如/other-page
)。如果为false
,则允许父路由加载。
下一篇:Angular子路由完全无法导航