当在多个路由文件中定义了NotFoundComponent组件时,Angular会报错,因为每个组件只能在一个模块中被定义一次。为了解决这个问题,我们可以采取以下步骤:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NotFoundComponent } from './not-found.component';
@NgModule({
declarations: [NotFoundComponent],
imports: [CommonModule],
exports: [NotFoundComponent]
})
export class NotFoundModule { }
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NotFoundModule } from './not-found/not-found.module';
@NgModule({
declarations: [],
imports: [
CommonModule,
NotFoundModule
]
})
export class AppModule { }
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NotFoundModule } from './not-found/not-found.module';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', loadChildren: () => NotFoundModule }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
通过以上步骤,我们在多个路由文件中定义NotFoundComponent时将不会再出现冲突,并且可以正确地使用该组件。