在 Angular 4 中使用 ID 进行路由 [英] Routing With ID in Angular 4

查看:25
本文介绍了在 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.

app-routing.module.ts

app-routing.module.ts

    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 进行路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆