Angular2 Routing: persisting route tabs and child routes

前端 未结 1 853
萌比男神i
萌比男神i 2021-02-05 07:22

Angular Community!

I\'m currently rewriting AngularJS app to Angular 2. I want to solve problem which could be described as: route tabs + child routes.

So, basic

1条回答
  •  后悔当初
    2021-02-05 08:12

    I understand you have two different questions:

    1- How to prevent the destruction of the component when you leave it. 2- implementing child routes.

    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) For the child routes I'll just put 2 examples:

    Ex1: regular child routing

    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: When the child routes belongs to another module

    Code for higher 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' }
      ]
    },
    

    `

    0 讨论(0)
提交回复
热议问题