在Angular 9中实现复杂的子/父导航可以通过使用路由器和路由守卫来完成。下面是一个包含代码示例的解决方案:
首先,创建一个父组件和多个子组件。在这个示例中,我们创建了一个父组件ParentComponent
和两个子组件Child1Component
和Child2Component
。
在父组件的HTML模板中,添加一个导航栏,用于切换子组件。
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ParentComponent } from './parent.component';
import { Child1Component } from './child1.component';
import { Child2Component } from './child2.component';
const routes: Routes = [
{
path: '',
component: ParentComponent,
children: [
{ path: 'child1', component: Child1Component },
{ path: 'child2', component: Child2Component }
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ParentRoutingModule { }
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ParentComponent } from './parent.component';
const routes: Routes = [
{ path: '', component: ParentComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ChildRoutingModule { }
AuthGuard
守卫。import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// 在这里添加自定义的授权逻辑
const isAllowed = true; // 假设始终允许导航
if (!isAllowed) {
// 如果不允许导航,则重定向到其他页面
this.router.navigate(['/other']);
}
return isAllowed;
}
}
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ParentComponent } from './parent.component';
import { Child1Component } from './child1.component';
import { Child2Component } from './child2.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{
path: '',
component: ParentComponent,
canActivate: [AuthGuard],
children: [
{ path: 'child1', component: Child1Component },
{ path: 'child2', component: Child2Component }
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ParentRoutingModule { }
``