在Angular中,可以使用路由守卫来处理未知路由。
首先,创建一个名为"NotFoundComponent"的组件,用于显示404错误页面。可以使用以下命令来生成该组件:
ng generate component NotFound
然后,在路由模块中,添加一个通配符路由,将它指向NotFoundComponent。在这个通配符路由中,可以使用**
来匹配任何未知路由。
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { NotFoundComponent } from './not-found/not-found.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
// 添加通配符路由
{ path: '**', component: NotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
接下来,在NotFoundComponent的模板文件中,添加404错误信息。
404 - 页面不存在
对不起,您访问的页面不存在。
最后,在app.component.html中,添加
标签,用于显示对应路由的组件。
现在,当用户访问一个未知路由时,将会显示NotFoundComponent组件,即404错误页面。
请注意,如果你有其他路由配置,确保将通配符路由放在最后,以便先匹配已知路由。