命名路由器插座导致 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>

showGeneric 的值在 app.component.ts 文件中最初设置为 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: '**',pathMatch: 'full'
 }
]

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

在本地运行应用程序并尝试导航到 http://localhost:4200/generic 时,我收到 错误:未捕获(承诺):错误:无法匹配任何路由。 URL Segment: 'generic'。 我无法弄清楚究竟是什么导致了这个问题。请帮我解决这个问题。

解决方法

正如@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,loadChildren: () =>
          import('./non-generic/non-generic.module').then(
            m => m.NonGenericModule
          )
      }
    ]
  },{
    path: '**',pathMatch: 'full'
  }
];

在html中

<a [routerLink]='["generic"]'>Generic</a> |
<a [routerLink]='["non-generic"]'>Non Generic</a> | 

<router-outlet></router-outlet>

Sample Demo(检查控制台)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...