angular - 命名路由器出口导致 Angular 11 应用程序中出现“无法匹配任何路由”错误
问题描述
我在 Angular 11 应用程序中使用命名路由器插座。app.component.html 文件中的代码是
<ng-container *ngIf="showGeneric">
<router-outlet name="general">
</router-outlet>
</ng-container>
<ng-container *ngIf="!showGeneric">
<router-outlet name="non-general">
</router-outlet>
</ng-container>
在 app.component.ts 文件中,showGeneric 的值最初设置为 true。
app-routing.module.ts 文件中的代码是
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NonGenericComponent } from './non-generic/main-component/non-generic.component';
import { GenericComponent } from './generic/main-component/generic.component';
const routes: Routes = [
{
path: '',
redirectTo: 'generic',
pathMatch: 'full'
},
{
path: 'generic',
component: GenericComponent,
loadChildren: () => import('./generic/generic.module').then(m => m.GenericModule),
outlet: 'general'
},
{
path: 'non-generic',
component: NonGenericComponent,
loadChildren: () => import('./non-generic/non-generic.module').then(m =>
m.NonGenericModule),
outlet: 'non-general'
},
{
path: '**',
redirectTo: 'generic',
pathMatch: 'full'
}
]
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在本地运行应用程序并尝试导航到 http://localhost:4200/generic 时出现错误:未捕获(承诺中):错误:无法匹配任何路由。URL 段:“通用”。我无法弄清楚究竟是什么导致了这个问题。请帮我解决这个问题。
解决方案
正如@mJehanno 所提到的,不需要命名路由器出口来实现此功能
删除命名的路由器出口并简单地将子路由传递给路由器配置以加载此模块
const routes: Routes = [
{
path: '',
redirectTo: 'generic',
pathMatch: 'full'
},
{
path: 'generic',
component: GenericComponent,
children: [
{
path: '',
loadChildren: () =>
import('./generic/generic.module').then(m => m.GenericModule)
}
]
},
{
path: 'non-generic',
component: NonGenericComponent,
children: [
{
path: '',
loadChildren: () =>
import('./non-generic/non-generic.module').then(
m => m.NonGenericModule
)
}
]
},
{
path: '**',
redirectTo: 'generic',
pathMatch: 'full'
}
];
在 html
<a [routerLink]='["generic"]'>Generic</a> |
<a [routerLink]='["non-generic"]'>Non Generic</a> |
<router-outlet></router-outlet>
示例演示(检查控制台)
推荐阅读
- python - CSV MNIST 数据集:ValueError:Shapes (None, 10) 和 (None, 28, 10) 不兼容
- python-3.x - 如何检测我的图像是否被截断并以线程安全的方式加载它?
- c++ - 定义一个全局变量模板?
- android - 当语言选择阿拉伯语时,如何设置短信验证布局的 RTL?
- javascript - 在没有“https”或“www”的情况下如何隔离URL的域名?
- firebase - Firebase 保留用户计数不匹配
- python - 我正在尝试学习从 API 请求、加载和解析 Json 数据。我收到一个值错误
- function - 如何使用命令切换到终端普通模式?
- firebase - Web 应用程序的 Firebase 动态链接
- sql - MSSQL 选择父母 ID 值