首页 > 解决方案 > 命名路由器出口导致 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 段:“通用”。我无法弄清楚究竟是什么导致了这个问题。请帮我解决这个问题。

标签: angulartypescriptangular-routingrouter-outlet

解决方案


正如@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>

示例演示(检查控制台)


推荐阅读