4中使用ID进行路由

4中使用ID进行路由

本文介绍了在Angular 4中使用ID进行路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 4中进行路由时需要帮助.我想显示这样的URL.Localhost:4200/user/1(如果我单击第一个用户的查看详细信息).我对如何做到这一点感到困惑.我在下面的代码中已尽力而为,但仍然无法正常工作.

I need help in my routing in Angular 4. I want to display the URL like this. Localhost:4200/user/1 if i clicked the view details of the first user. I'm a bit confused on how to to this. I've tried my best in my code below but it still doesn't work.

const appRoutes: Routes = [
    { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
    { path: 'dashboard', component: DashboardComponent },
    { path: 'user', component: UserComponent, children: [

        { path: 'create-new-user', component: CreateNewUserComponent },
        { path: 'user-list', component: UserListComponent },
        { path: 'user-detail/:id', component: UserDetailComponent },

]},
];


@NgModule({
    imports: [RouterModule.forRoot(appRoutes)],
    exports: [RouterModule]
})
export class AppRoutingModule {

}

推荐答案

前一段时间我遇到了这个问题.这里的问题是您拥有的路由配置.您无法转到/user/1,因为您已将"user-details"路由定义为"user"路由的子级.您只需导航到'/user/user-detail/1'或简单地使用指向您的详细信息组件的路径':id'定义新的子路线,现在就可以导航至'/user/1'

I had this very problem a while ago. The problem here is the routes configurations you have. You cannot go to /user/1 because you defined the 'user-details' route as a child of the 'user' route. You either have to navigate to '/user/user-detail/1' or simply define a new child route with path ':id' pointing to your details component and you'll be able now to navigate to '/user/1'.

总结一下:路线:

const appRoutes: Routes = [
    ...
    { path: 'user', component: UserComponent, children: [

        ...
        { path: 'user-detail/:id', component: UserDetailComponent },

    ]},
];

您可以导航到'/user/user-details/1'.路线:

you can navigate to '/user/user-details/1'.With the routes:

const appRoutes: Routes = [
    ...
    { path: 'user', component: UserComponent, children: [

        ...
        { path: ':id', component: UserDetailComponent },

    ]},
];

您可以导航到'/user/1'.希望对您有帮助.

you can navigate to '/user/1'.Hope it helps you.

这篇关于在Angular 4中使用ID进行路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:52