带有“**”的 Angular 模块化路由没有匹配的路由

问题描述 投票:0回答:3

在每个单独的子模块中使用routes.forchild是模块化应用程序的好方法,很好。但如何处理所有不匹配的网址呢?如果我实现到主(引导)

AppRoutingModule
以下路线

const routes: Routes = [
  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'home', component: HomeComponent},
  {path: '**', ErrorComponent, pathMatch: 'full'},

除非存在正确的子路由,否则“**”路由将随时执行。

如果我在最后一个子 module.ts 中实现这样的

{path: '**', ErrorComponent },

它永远不会起作用。

唯一的方法似乎是所有路由都在公共根模块中,但至少以智能方式无法实现模块化(组件和路由在同一个文件夹中)

angular angular-routing custom-error-pages
3个回答
1
投票

如果要处理所有不匹配的 URL,则需要将路径为“**”的包罗万象的路由放置在主路由模块(在应用程序中引导的模块)中。这是因为只有当应用程序中没有其他路由与请求的 URL 匹配时,捕获所有路由才会被激活。

如果将 catch-all 路由放在子模块中,效果不会很好,因为子模块只处理自己范围内的路由,而主路由模块才是可以访问完整 URL 的模块。

延迟渲染是一个很棒的工具。

const routes: Routes = [
  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'home', component: HomeComponent},
  {path: '**', component: ErrorComponent, pathMatch: 'full'},
];
const routes: Routes = [
  {path: 'feature1', component: Feature1Component},
  {path: 'feature2', component: Feature2Component},
];

路由配置中的loadChildren属性是功能模块延迟加载的工具。

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'feature',
    loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
  },
  { path: '**', component: ErrorComponent, pathMatch: 'full' }
];

0
投票

对于apache服务器 .htaccess 文件内 (perl)

ErrorDocument 和 RewriteRule 指令中的 /404 是自定义错误组件的 URL。您需要将其替换为 Angular 应用程序中组件的实际 URL。

ErrorDocument 404 /404

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /404 [L]

到目前为止它做了什么

RewriteEngine指令用于开启Apache的URL重写引擎,RewriteCond和RewriteRule指令用于将所有无效的URL请求重定向到自定义错误页面。

经过额外修改 https://httpd.apache.org/docs/2.4/howto/htaccess.html


0
投票

如果 Angular Route 找不到路径,则有不同的情况,例如。 .de/pageDoesNotExist-404 在 Angular 应用程序内,那么建议的答案是正确的

  {
    path: 'feature',
    loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
  },
  { path: '**', component: ErrorComponent, pathMatch: 'full' }

并且将显示正确的错误页面。

但是,如果从浏览器直接调用的 URL 路径错误:https://....de/pageDoesNotExist-404

角度应用程序不会覆盖不匹配的情况,apache 服务器将执行错误例程。

© www.soinside.com 2019 - 2024. All rights reserved.