【问题标题】:Why does the order of NgModule imports matter?为什么 NgModule 导入的顺序很重要?
【发布时间】:2017-06-27 22:49:15
【问题描述】:

我一直在阅读 Angular 教程,并在阅读 HTTP 部分 https://angular.io/docs/ts/latest/tutorial/toh-pt6.html 时注意到,在 NgModule 中声明导入的顺序会影响应用程序是否正常工作。我想知道为什么会这样。

这尤其有效:

@NgModule({ 进口:[ 浏览器模块, 表单模块, Http模块, InMemoryWebApiModule.forRoot(InMemoryDataService), 应用路由模块 ], ... })

但以下没有。英雄列表没有加载。请注意,HttpModule 是在 InMemoryWebApiModule 之后声明的:

@NgModule({ 进口:[ 浏览器模块, 表单模块, InMemoryWebApiModule.forRoot(InMemoryDataService), Http模块, 应用路由模块 ], ... })

本教程使用 Angular 2.4.4。我在 Firefox 和 IE 中都注意到了这个问题。我在 Google 搜索中没有发现任何可以表明问题根源的内容。

【问题讨论】:

    标签: angular


    【解决方案1】:

    提供者的顺序很重要,对于导出的组件、指令或管道来说无关紧要,因为冲突会导致错误。

    InMemoryWebApiModule.forRoot(InMemoryDataService), 覆盖 Http,如果稍后提供 HttpModule,则此 oVerriding 将变为无效。 稍后添加的提供程序会使用相同的密钥覆盖已注册的提供程序。

    【讨论】:

    • 感谢您的帮助。我在 InMemoryWebApi 的自述文件中发现了这一点:“始终在 HttpModule 之后导入 InMemoryWebApiModule,以确保 InMemoryWebApiModule 的 XHRBackend 提供程序取代所有其他提供程序。”基本上就是你说的。
    • 导入顺序也很重要,我注意到如果我将 AppRoutingModule 放在自定义模块之后,它将将该自定义模块加载为第一页而不是 AppRoutingModule 中定义的页面
    【解决方案2】:

    是的。如果一个模块依赖于另一个模块,顺序很重要。

    【讨论】:

      猜你喜欢
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多