更新时间:2022-06-14 09:30:17
我知道您有两个不同的问题:
I understand you have two different questions:
1- 如何防止组件在离开时被破坏.2- 实现子路由.
1- How to prevent the destruction of the component when you leave it. 2- implementing child routes.
1) 目前 Angular 没有方便的方法来做到这一点.如果它们是像 canDestroy() 这样的生命周期钩子,我们会很感激.
1) For now Angular doesn't have convenient way to do this. We would apreciate it if they were a life cycle hook called like canDestroy().
无论如何,您可以使用不可路由的选项卡来执行此操作,也可以将数据存储在不会被破坏的更高组件上.
Anyway you can do this either using non routable tabs OR just store your data on a higher component that doesn't get destroyed.
2) 对于子路由,我只举两个例子:
2) For the child routes I'll just put 2 examples:
Ex1:常规子路由
const AdminRoutes: Routes = [
{
path: '',
component: AdminComponent,
children: [
{
path: 'users',
component: UsersComponent,
children: [
{ path: 'acces', component: AccesComponent, data: { preload: true} },
{ path: 'roles', component: RolesComponent, data: { preload: true} },
{ path: '', redirectTo: '/admin/users/acces', pathMatch: 'full' },
{ path: '**', redirectTo: '/admin/users/acces', pathMatch: 'full' },
],
data: { preload: true}
},
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: '**', redirectTo: '/login', pathMatch: 'full' }
]
},
EX2:当子路由属于另一个模块时
EX2: When the child routes belongs to another module
更高模块的代码
`
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent, data: { preload: true} },
{
path: 'admin',
loadChildren: 'app/modules/admin/admin.module#AdminModule',
canActivate: [AuthGuardService],
data: { preload: true}
},
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: '**', redirectTo: '/login', pathMatch: 'full' }
`
自己模块中子路由的代码
Code for child routes in their own module
`
const AdminRoutes: Routes = [
{
path: '',
component: AdminComponent,
children: [
{
path: 'users',
component: UsersComponent,
children: [
{ path: 'acces', component: AccesComponent, data: { preload: true} },
{ path: 'roles', component: RolesComponent, data: { preload: true} },
{ path: '', redirectTo: '/admin/users/acces', pathMatch: 'full' },
{ path: '**', redirectTo: '/admin/users/acces', pathMatch: 'full' },
],
data: { preload: true}
},
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: '**', redirectTo: '/login', pathMatch: 'full' }
]
},
`