【问题标题】:In what order should i import modules in my shared module我应该以什么顺序在我的共享模块中导入模块
【发布时间】:2018-04-16 20:36:30
【问题描述】:

我创建了一个如下所示的共享模块。我在某处读过进口订单很重要,但我现在找不到那个链接。在某些地方它工作正常,但在其他地方我得到错误。我想知道这些模块的顺序以避免任何错误。

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import 'hammerjs';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { MaterialModule } from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
import { CoreModule } from './core/core.module';

// NOTE: The import order matters.
const modules = [
  CommonModule,
  CoreModule,
  ReactiveFormsModule,
  FormsModule,
  HttpClientModule,
  MaterialModule,
  FlexLayoutModule,
];

@NgModule({
  imports: modules,
  exports: modules
})
export class DependenciesModule { }

【问题讨论】:

  • at other places i am getting error. 是什么错误?
  • @yurzui 道歉,我现在没有收到那个错误。我认为我的团队成员修复了它。该错误与 FormsModule 或 MaterialModule 有关,因为顺序不正确。我想知道这些模块的加载顺序。
  • 我想知道错误是什么

标签: angular node-modules


【解决方案1】:

应用范围的单例提供程序

首先,我强烈建议不要在共享模块中包含应用程序范围的单例providers。导入共享模块的延迟加载模块会生成自己的服务副本。

CoreModule(如果它包含应用程序范围的提供程序)和HttpClientModule 不应在SharedModule 中。

另见:

供应商优先级

您应该知道所有提供程序都添加到同一个注入器中。(root 或通过延迟加载创建)

当两个导入的模块同时加载时,列出具有相同标记的提供者,第二个模块的提供者“获胜”。当 Angular 为该令牌注入服务时,它会创建并交付由第二个提供者创建的实例。

如果模块 A 为令牌“X”提供服务并导入一个也为令牌“X”提供服务的模块 B,则模块 A 的服务定义“胜出”。

根 AppModule 提供的服务优先于导入模块提供的服务。 AppModule 总是胜出。

另见:

路由

配置中路由的顺序很重要,这是设计使然。

路由器在匹配路由时使用先匹配获胜策略,因此应将更具体的路由放在不太具体的路由之上。

这也意味着如果你有两个带有路由配置的模块,你应该以正确的顺序导入它们。

另见:


如果这些模块仅包含组件、指令和管道,那么您订购模块的方式没有区别。它们被合并到传递模块中。

另见:

【讨论】:

  • 关于服务 我昨天刚看了官方文档,我知道服务不应该在共享组件中提供。在我的 CoreModule 中,我有需要经常使用的组件。共享模块中的模块顺序是我在任何地方都找不到的。
  • 库开发人员有什么办法可以解决这个问题吗?假设我使用 InjectionToken 将可插入逻辑放入组件中。我在我的功能模块中提供了 InjectionToken,但目的是如果它在其他任何地方提供,那么该提供者应该覆盖我的。如果你必须知道导入的秘密顺序,这不是一个好的 API,像 MAT_MENU_SCROLL_STRATEGY 这样的令牌有这个问题。
【解决方案2】:

试试这样:

在您的 DependenciesModule 中导出所有模块并将其导入另一个模块。

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { MaterialModule } from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
import { CoreModule } from './core/core.module';

import 'hammerjs';

@NgModule({
  imports: [],
  exports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    MaterialModule,
    FlexLayoutModule,
    CoreModule
  ]
})
export class DependenciesModule { }

【讨论】:

    猜你喜欢
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    相关资源
    最近更新 更多