如何在 Angular 项目中为自定义 404 页面设置路由

How to set up a route for custom 404 page in Angular Project

在我的 Angular 项目中,我有一个名为 'wrongRouteComponent' 的组件用于自定义 404 页面。当有人进入非预定义路线时,它应该显示 'wrong-route.component.html'。我不明白该怎么做。

这是我用过的'app-rouring.module.ts'

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

// Required components for which route services to be activated
import { LandingComponent } from '../../components/landing/landing.component';
import { DashboardComponent } from '../../components/dashboard/dashboard.component';
import { UserprofileComponent } from '../../components/userprofile/userprofile.component';
import { WrongRouteComponent } from '../../components/wrong-route/wrong-route.component';

const routes: Routes = [
  { path: '', component: LandingComponent},
  { path: '/dashboard', component: DashboardComponent},
  { path: '/userprofile', component: UserprofileComponent},

  //Wrong route
  { path: '404', component: WrongRouteComponent},

];

谁能告诉我应该对

添加哪些更改
{ path: '404', component: WrongRouteComponent},

请将路径 '404' 更改为 **

所以,路线应该是

const routes: Routes = [
  { path: '', component: LandingComponent},
  { path: '/dashboard', component: DashboardComponent},
  { path: '/userprofile', component: UserprofileComponent},

  //Wrong route
  { path: '**', component: WrongRouteComponent},

];

你可以做到

{
    path        : '**',
    pathMatch   : 'full',
    component   : WrongRouteComponent
}

最后将这个通配符路由放入你的路由文件中的routes数组中。

希望对你有所帮助

wild card route 将捕获所有你不知道的路径(常量中未定义的路由)。未定义 URL 导致路由器抛出错误并使应用程序崩溃。

通常路由是从上到下读取的,这就是为什么在路由列表末尾保留通配符路由 ('**') 很重要。 如果你把这条放在最前面,所有其他路线都将被视为未定义。

您可以如下使用。

{path: ‘not-found’ , component: ‘NotFoundComponent’}
{path: ‘**’ , redirectTo: ‘/not-found’}

或者

 { path: '**', component: NotFoundComponent}

这是对我有用的答案。

const routes: Routes = [
  { path: '', component: LandingComponent},
  { path: '/dashboard', component: DashboardComponent},
  { path: '/userprofile', component: UserprofileComponent},

  //Wild Card Route
  { path: '**', pathMatch   : 'full', component: WrongRouteComponent},

];