gpt4 book ai didi

Angular 路由给出了不正确的组件

转载 作者:行者123 更新时间:2023-12-01 23:51:03 24 4
gpt4 key购买 nike

我对 Angular 路由有疑问。当我尝试访问 my.domain/new-york 时,我得到了正确的页面 (HomeComponent)但是,当我尝试转到 my.domain/new-york/search 时,我得到了 HomeComponent 而不是 SearchComponent。我做错了什么?

const routes: Routes = [
{
path: '',
component: BasicComponent,
children: [
{
path: '',
component: HomeComponent,
data: {
headerDark: true
}
},
{
path: ':city',
component: HomeComponent,
data: {
headerDark: true
},
children: [
{
path: ':category',
component: HomeComponent
},
{
path: 'search',
component: SearchComponent,
data: {
headerDark: true
}
},
]
},
]
}
];

更新:我使用两个模块:

const routes: Routes = [
{
path: '',
loadChildren: () => import('./modules/basic/basic.module').then(mod => mod.BasicModule),
runGuardsAndResolvers: 'always'
},
{
path: 'dashboard',
canActivate: [AuthService],
loadChildren: () => import('./modules/dashboard/dashboard.module').then(mod => mod.DashboardModule)
},
{
path: '**',
redirectTo: '/'
}
];

更新 2:示例 https://stackblitz.com/edit/angular-ghafx6?file=src%2Fapp%2Forders%2Forders-routing.module.ts

最佳答案

如果您使用动态路由,路由顺序非常重要。

这里的问题是search在城市名称被视为 category 之后因为categorydynamic route它出现在 static route 之前.所以总是推荐dynamic route必须在最后。

对于您的问题,改变您以这种方式路由将解决您的问题。

 const routes: Routes = [
{
path: '',
component: BasicComponent,
children: [
{
path: '',
component: HomeComponent,
data: {
headerDark: true
}
},
{
path: ':city',
component: HomeComponent,
data: {
headerDark: true
},
children: [
{
path: 'search',
component: SearchComponent,
data: {
headerDark: true
}
},
{
path: ':category',
component: HomeComponent
},
]
},
]
}
];

参见 Stackblitz供引用

已编辑

根据您的 stackblitz,需要进行以下 2 处更改。

  1. city.component.html

    已添加 <router-outlet></router-outlet>

  2. orders.component.html

    <a [routerLink]="['/new-york']">
City
</a>
<a [routerLink]="['/new-york/shops']">
Category
</a>
<a [routerLink]="['/new-york/search']">
Search
</a>
<router-outlet></router-outlet>

参见 Stackblitz供引用

关于 Angular 路由给出了不正确的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63501744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com