【问题标题】:Angular forRoot and forChildAngular forRoot 和 forChild
【发布时间】:2020-01-17 03:50:39
【问题描述】:

我正在尝试了解 Angular 的 forRootforChild 静态方法。

我有两个问题。

1) 下面的代码 sn-ps 是否等效?

这个:

// App Module
const routes = [
  { path: '', pathMatch: 'full', component: HomeComponent },
  { path: 'dashboard', component: DashboardComponent }
];

const routing: ModuleWithProviders = RouterModule.forRoot(routes);

用这个:

// App Module:
const routes = [
  { path: '', pathMatch: 'full', component: HomeComponent },
];

const routing: ModuleWithProviders = RouterModule.forRoot(routes);

// Dashboard Module:
const routes = [
    { path: 'dashboard', component: DashboardComponent }
];

const routing: ModuleWithProviders = RouterModule.forChild(routes);

2) 它们是否作用于同一个对象?

据我了解,forRoot 方法是实例化路由器服务的方法。它添加了第一条路线。 forChild 将第二条路由添加到同一个对象。

正确吗? forRootforChild 最终是否在同一个实例上工作?

【问题讨论】:

  • 这两个问题是的
  • thx @julianobrasil 还有一个简短的问题:我在我的应用程序中使用了 Ionic。在我在 AppModule 中的导入中,我有:'IonicModule.forRoot()' withforRoot() 我可以将配置传递给 IonicModule。如果我不通过任何配置,我也可以在没有 forRoot() 的情况下编写“IonicModule”。这也是等价的吧?
  • 通常需要调用forRoot(),因为这是导出模块内容的方式。如果不调用该函数,您可能不会导入所有必要的导出内容(forRoot() 没有任何参数可能具有合理的默认值)。
  • 这能回答你的问题吗? Angular: forRoot/forChild methods usage?

标签: angular


【解决方案1】:

仅在根 AppRoutingModule 中调用 RouterModule.forRoot() (或 AppModule,如果您在那里注册顶级应用程序路由)。在任何其他模块中,您必须调用 RouterModule.forChild 方法来注册额外的路由。

https://angular.io/guide/router

这里是RouterModule.forRoot()和RouterModule.forChild()的区别

RouterModule.forRoot()

  1. 声明路由器指令
  2. 管理我们的路线配置

  3. 注册路由器服务

  4. 用于应用程序一次

RouterModule.forChild()

  1. 声明路由器指令
  2. 管理我们的路线配置
  3. 不注册路由器服务
  4. 用于功能模块

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多