【问题标题】:How to correctly handle 404 when using modular routing in Angular 10在Angular 10中使用模块化路由时如何正确处理404
【发布时间】:2021-12-31 02:50:05
【问题描述】:

我无法使用模块化路由在 Angular 10 应用程序中正确处理 404 页面。

我的代码结构如下:

|> app
|-- app.module.ts
|-- app-routing.module.ts
|-- app.component{ts, spec.ts, scss, html}
|-> pages
|--- pages.module.ts
|--> home-page
|---- home-page.module.ts
|---- home-page-routing.module.ts
|---> home-page
|----- home-page.component{ts, spec.ts, scss, html}
|--> test-page
|---- test-page.module.ts
|---- test-page-routing.module.ts
|---> test-page
|----- test-page.component{ts, spec.ts, scss, html}

(截断的)全局应用程序路由模块具有如下配置的 404 处理程序:

...
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },

  // If the following line is not commented out,
  // You are unable to navigate to either the 'Home' or 'Test' pages.
  // { path: '**', component: PageNotFoundComponent },
];

...

我遇到的问题是 Angular 匹配 ./app/app-routing.module.ts 中的全局 404 处理程序并解析到该路由。

Here's a short stackblitz that provides an example of my experience (注意:Stackblitz 示例实际上运行的是 Ng12,而我们的应用程序运行的是 Ng10 - 两者表现出相同的行为)

我的目标是让全局 404 处理程序或重定向工作,同时继续将我们所有的页面路由定义在各自的模块路由文件中。

如果可以,可以这样做吗?

【问题讨论】:

    标签: javascript angular typescript angular-router


    【解决方案1】:

    我查看了您的 Stackblitz,问题是 AppRoutingModule 是在 PagesModule 之前导入的。

    您应该首先导入PagesModule,因为它们的路由具有更高的优先级。

      imports: [
        BrowserModule,
        RouterModule,
        FormsModule,
        PagesModule,
        AppRoutingModule,
      ],
      declarations: [AppComponent],
      bootstrap: [AppComponent],
    })
    export class AppModule {}
    

    另一个(更好的)解决方案是延迟加载模块:

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

    这样您就不必将整个 PagesModule 导入您的 AppModule。

    【讨论】:

    • 感谢您的简洁回复。重新排序优先级非常简单(可能应该更明显)。关于您的推荐,假设有很多页面。似乎最好(以某种方式)根据需要延迟加载各个页面,但实现这一点的唯一明显方法是在 app-routing.module 定义中定义它们的路由。有没有办法实现推荐,同时将路线保留在各自的页面模块中?
    猜你喜欢
    • 2016-10-03
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 2017-05-07
    相关资源
    最近更新 更多