首页 > 解决方案 > 带有**的Angular 9路由器重定向无法正常工作

问题描述

我有**路径应该加载landingif route not found,但它每次加载登陆例如 www.page.com/contacts -> 显示登陆 www.page.com/contacts url,但联系人存在于我的页面中,如何仅加载它如果找不到路线?

const routes: Routes = [
  {
    path: AppRoutes.admin,
    loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
    pathMatch: 'full'
  },
 {
path: "**",
loadChildren: () => import('./public/landing/landing.module').then(m => m.LandingModule),
 }
  {
    path: '',
    loadChildren: () => import('./public/landing/landing.module').then(m => m.LandingModule),
  },
  {
    path: `${AppRoutes.content}/:name`,
    loadChildren: () => import('./public/contents/contents.module').then(m => m.ContentsModule),
  },

  {
    path: AppRoutes.cars,
    loadChildren: () => import('./public/cars/cars.module').then(m => m.CarsModule),
  },
  {
    path: AppRoutes.private,
    loadChildren: () => import('./public/tours/tours.module').then(m => m.ToursModule),
  },
  {
    path: AppRoutes.vehicles,
    loadChildren: () => import('./public/carlist/carlist.module').then(m => m.CarlistModule),
  },
  {
    path: `${AppRoutes.paymentsCancel}`,
    loadChildren: () => import('./public/cancel/cancel.module').then(m => m.CancelModule),
  },
  {
    path: `${AppRoutes.paymentsConfirm}`,
    loadChildren: () => import('./public/success/success.module').then(m => m.SuccessModule),
  },

];

是否有任何简单的方法可以将所有错误的 url 重定向到特定模块?我的意思是如果找不到路由器网址。

标签: angulartypescriptprogressive-web-appsangular-universal

解决方案


您需要将通配符路线放在底部。路由器检查它可以找到的第一个匹配项

const routes: Routes = [
  // ...
  {
    path: `${AppRoutes.paymentsConfirm}`,
    loadChildren: () => import('./public/success/success.module').then(m => m.SuccessModule),
  },
  {
    path: "**",
    loadChildren: () => import('./public/landing/landing.module').then(m => m.LandingModule),
  }
];

这在文档中有详细说明

路线顺序

路由的顺序很重要,因为路由器在匹配路由时使用先匹配获胜策略,因此更具体的路由应该放在不太具体的路由之上。首先列出具有静态路径的路由,然后是与默认路由匹配的空路径路由。通配符路由位于最后,因为它匹配每个 URL,并且路由器仅在没有其他路由首先匹配时才选择它。


推荐阅读