【问题标题】:Angular 2 complex nested routingAngular 2 复杂的嵌套路由
【发布时间】:2017-01-10 01:44:59
【问题描述】:

我正在将 Angular 2 应用从 2.0.0-beta.0 升级到 2.4

我有复杂的路由,有许多重复使用的组件有多个孩子;我举一个简化的例子:

└─Home
  ├─Company
  | ├─Requests
  | └─Users
  |   ├─Subscriptions
  |   | └─Requests
  |   └─Requests
  ├─Users
  | ├─Subscriptions
  | | └─Requests
  | └─Requests
  └─Subscriptions
    └─Requests

如您所见,Users 组件和 Subscriptions 组件(带有各自的子组件)被多次使用,Request 模块也是 Users 和 Company 的子组件。

这在 Beta 0 中很简单,因为组件可以有自己的单独路由。但是,我一直无法在当前版本的 Angular 中找到一个好方法。我可以将每个带有子组件的重用组件转换为带有引导组件的模块,但这会增加更多代码并且不会很灵活。

有没有办法做到这一点,而不使每个具有子模块的重用组件?

【问题讨论】:

    标签: angular routing angular2-routing


    【解决方案1】:

    简单地使用 'children' + 'redirectTo' 怎么样?

    const routes: Routes = [
      { path: '', pathMatch: 'full', component: HomeComponent },
      { path: 'company', children: [
        { path: '', pathMatch: 'full', component: CompanyComponent},
        // path '/company/requests' will redirectTo '/requests'
        { path: 'requests': redirectTo: '/requests' }, 
        { path: 'users': redirectTo: '/users' },
      ]},
      { path: 'users', children: [
        { path: '', pathMatch: 'full', component: UsersComponent },
        { path: 'subscriptions', redirectTo: '/subscriptions' },
        { path: 'requests', redirectTo: '/requests' }
      ]},
      { path: 'subscriptions', children: [
        { path: '', pathMatch: 'full', component: SubscriptionsComponent },
        { path: 'requests', redirectTo: '/requests' },
      ]},
      { path: 'requests', component: RequestsComponent },
    ];
    

    【讨论】:

    • 我可以这样做,但是如果您有 { path: 'users', ...},那么这些路线将重复与第一次完全相同。我想避免这种情况。
    • 添加了一堆'redirectTo'。看看有没有帮助。
    • 有趣...不幸的是,我需要保持路径的全长,因为我在路由器插座中嵌套了路由器插座,并且所有以前的组件仍然是打开的。看来我必须屈服于不可避免的情况,只使用嵌套模块。
    【解决方案2】:

    我通过将此代码放入我的每个组件中解决了这个问题:

    在 foo.component.ts 中:

    import { BarComponent } from './bar.component'
    export const FooRouting: Routes = [
        { path: 'Bar', component: BarComponent }
    ]
    

    在 home.ts(模块)中

    import { FooComponent, FooRouting } from './foo.component'
    import { BarComponent } from './bar.component'
    
    @NgModule({
        imports: [
            ...
            RouterModule.forRoot([
                { path: '', component: FooComponent, children: FooRouting }
                { path: 'Bar', component: BarComponent }
            ])
            ...
        ],
        ...
    )}
    

    制作:

    └─Home
      ├─Foo
      | └─Bar
      └─Bar
    

    【讨论】:

      猜你喜欢
      • 2016-09-09
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 2017-06-11
      • 1970-01-01
      相关资源
      最近更新 更多