Angular 2 RC5路由器 - 嵌套路由

时间:2016-08-12 14:34:06

标签: angular2-routing

结构

app |- admin
         |- users
             |- userList.Component.ts
             |- userDetails.Component.ts
         |- admin.component.html (contains 'router-oulet')
         |- admin.component.ts
         |- admin.routes.ts
         |- admin.module.ts
    |- dogs
    |- app.component.html (contains 'router-oulet')
    |- app.component.ts
    |- app.routes.ts
    |- app.module.ts

app.routes.ts

const appRoutes: Routes = [

    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },

    { path: 'dogs', component: DogListComponent, canActivate: [AuthGuard] },
    { path: 'dog/:id', component: DogDetailsComponent, canActivate: [AuthGuard]},
];

export const routing = RouterModule.forRoot(appRoutes);

admin.routes.ts

const adminRoutes: Routes = [

    {
        path: 'admin',
        component: AdminComponent,
        canActivate: [AdminGuard],
        children: [

            { path: '', redirectTo: '/admin/users' },

            { path: 'users', component: AdminUserListComponent },
            { path: 'user/:id', component: AdminUserDetailsComponent },
        ]
    },

];

export const adminRouting = RouterModule.forChild(adminRoutes);

admin.userList.Component.ts

this._router.navigate(['/admin/user/', id]);

尝试从AdminUserList(' admin / users')导航到AdminUserDetails(' admin / user / someId'),但没有成功。

(每当我尝试导航到用户详细信息时,似乎滚动条会进一步下降)

任何解决方案?

1 个答案:

答案 0 :(得分:0)

您需要在管理路由中添加pathMatch: 'full'以进行默认重定向,

<强> admin.routes.ts

const adminRoutes: Routes = [

{
    path: 'admin',
    component: AdminComponent,
    canActivate: [AdminGuard],
    children: [

        { path: '', redirectTo: '/admin/users', pathMatch: 'full' },
        { path: 'users', component: AdminUserListComponent },
        { path: 'user/:id', component: AdminUserDetailsComponent },
    ]
 },
];

export const adminRouting = RouterModule.forChild(adminRoutes);

<强>更新

要导航回来,你有几种方法,

 // In the HTML
 <a [routerLink]="['/admin']" >Back</a> or <a [routerLink]="['/admin/users']" >Back</a>

 // Or create a back function and use in click binding in HTML
 goBack = () => {
    this.router.navigate(['/admin']);
    or this.router.navigate(['/admin/users']);
 }

希望这会有所帮助!!