当我输入与任何其他路由都不匹配的路径时,我无法弄清楚如何加载 404 路由。我设置路线的方式如下
const SITEROUTES: Routes = [
//...routes
{
path:'',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: '**',
loadComponent: () => import('./pages/site/page-not-found-page/page-not-found-page.component')
.then(mod => mod.PageNotFoundPageComponent)
}
]
我的所有路线均按预期加载,因此我认为包含它们并不重要。我显示这两个的原因是,如果我添加的路由与任何其他路由都不匹配,则它默认为
redirectTo
路由而不是通配符路由。如果我注释掉重定向路由,通配符路由会按照我的意愿触发,但是如果我不提供路由,它也会触发。
我将这两条路由放在数组的最后,甚至将
pathMatch: 'full
添加到通配符路由中,看看它是否会产生影响,但事实并非如此。我还在该应用程序中使用 standalone
组件,因此我将路线导入到我的 main.ts
文件中,如下所示
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(SITEROUTES),
provideAnimations()
]
};
bootstrapApplication(AppComponent, appConfig).catch(err => console.error(err));
我还通过
subscription
以编程方式将路由切换到我在 AppComponent
中设置的服务文件,如下所示
constructor(private router: Router, private navService: SidebarService){
this.navService.Route.subscribe(a => this.router.navigateByUrl(a));
}
其他一切都按我的预期工作,因此我认为目前不需要包含任何其他代码,也不知道还有什么相关。如果您需要查看其他内容,请告诉我,我将更新帖子以包含它。
请修改您的路线配置
const SITEROUTES: Routes = [
{
path: 'home',
component: HomeComponent
},
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: '**',
component: PageNotFoundPageComponent
}
];
通过此配置,当用户输入与任何其他路由都不匹配的 URL 时,路径为“**”的通配符路由将自动捕获它并加载 PageNotFoundPageComponent。
另外,请确保您已从 @angular/router 导入必要的组件以及路由和 RouterModule
希望对你有帮助..