我应该如何处理 Angular 中嵌套模块的路由

How should I handle routing with nested Module in Angular

我正在尝试以最佳方式处理 Angular 中嵌套模块的路由。

假设我用 URL localhost:5000 开始申请。我应该在左侧看到 HomeComponent 和一些内容,在右侧我有 <router-outlet> 应该呈现的地方 ContactComponent。如果我要转到 localhost:5000/info,那么 ContactComponent 应该替换为 InfoComponent。我怎样才能做到这一点?

这是我目前所拥有的: https://stackblitz.com/edit/angular6-material-components-demo-jb9y3u?file=src/app/home/home-routing.module.ts

(ContactComponent 未渲染,如果我转到 localhost:5000/info,则 InfoComponent 将从 AppComponent[=22= 渲染到 <router-outlet> ]

为了更好的解释图片:

在应用程序中试试这个-routing.module

const routes: Routes = [
  {
    path: "",
    component: HomeComponent,
    children: [
      {
        path: "",
        component: ContactComponent,
      },
      {
        path: "info",
        component: InfoComponent,
      },
    ]
  },
];

您现在对顶级 router-outlet(在 AppComponent 中)没有任何意义。如果它有一个目的(在说'/home'时匹配HomeComponent)那么你可以将第二个router-outlet中的第二个路由与'home'路由的一些children匹配( ContactComponent => '/home/contact' 和 InfoComponent => '/home/info').

您的路线有问题。 您应该了解更多有关使用儿童 属性 路线的信息。

另外,注意pathMatch

link: https://stackblitz.com/edit/angular6-material-components-demo-rfeaup

回复评论,是的,我被添加了延迟加载。否则,我看不出使用特色模块有什么意义。惰性模块是一个功能模块,它分离了一部分应用程序功能。如果您使用惰性模块,这对客户端来说会更好一些,因为客户端不应该等待所有应用程序加载,而是等待核心。

有关 Angular 应用程序中延迟加载的更多信息:https://angular.io/guide/lazy-loading-ngmodules

好吧,关于 "Children" - "contains all the child routes activated under the current route" - 根据官方文档。

我相信它对您也有帮助:https://angular.io/guide/router#child-route-configuration