可以使用通配符路由来解决这个问题。在Angular路由中,可以使用“”来表示任意路径。当路由器没有匹配到任何路由时,它会尝试匹配“”路由。可以将“**”路由到自定义的“not-found”组件或页面。
下面是一个具体的示例:
在app.module.ts中声明“not-found”组件:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NotFoundComponent } from './not-found/not-found.component';
const routes: Routes = [
// 其他路由
{ path: '404', component: NotFoundComponent },
{ path: '**', redirectTo: '/404' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在app.component.html中添加路由出口:
在not-found.component.html中添加自定义的“未找到”页面:
404 - 页面不存在
返回首页
这样,当路由器无法匹配到任何路由时,将会自动重定向到“/404”,显示自定义的“未找到”页面。