【问题标题】:Passing environment variables from one module to another in Angular 7在Angular 7中将环境变量从一个模块传递到另一个模块
【发布时间】:2019-10-06 18:24:32
【问题描述】:

我正在处理具有两个应用程序(应用程序 A,应用程序 B)的项目。这两个应用程序使用了大约 100 个组件。所以我创建了一个 Angular 库并将这些组件组织在模块中。一切正常。当我需要将环境传递给库中的模块时,我被卡住了。

@NgModule({
 imports:[
 LibModule2, // need to pass environment from LibModule1
 LibModule3,
]
})
export class LibModule1{
  export function forRoot(environment):ModuleWithProviders{
   return {
       ngModule:LibModule1,
       providers:[
        {provider:ENV, useValue:environment}
       ]
   }
 }
}


//App1

@NgModule({
  imports:[
   LibModule1.forRoot(environment)
  ]
})
export class AppModule(){}

我只需要应用程序中的 LibModule1。但也需要将环境传递给 LibModule2、LibModule3。我怎样才能做到这一点?我是否以错误的方式接近它?

【问题讨论】:

  • 可以尝试使用一个类来注入提供者值。并在课堂上有适当的吸气剂。 angular.io/guide/…
  • 仍然卡住。你能提供一个解决类似情况的代码示例吗?

标签: angular angular-module angular-library


【解决方案1】:

我有一段时间遇到这样的问题,我找到的最佳解决方案是:

将静态类添加到您的库模块中:

export class Lib1Module {
  static forRoot(config: any): ModuleWithProviders {
    return {
      ngModule: Lib1Module,
      providers: [{provide: 'config', useValue: config}]
    };
  }
}

export class Lib2Module {
  static forRoot(config: any): ModuleWithProviders {
    return {
      ngModule: Lib2Module,
      providers: [{provide: 'config', useValue: config}]
    };
  }
}

然后将environmentapp.module 传递给您的Lib1ModuleLib2Module 像这样:

imports:[
    CommonModule,
    BrowserAnimationsModule,
    ReactiveFormsModule,
    HttpClientModule,
    RouterModule,
    BrowserModule,
    FormsModule,
    GigLib1Module.forRoot(environment),
    GigLib2Module.forRoot(environment)
]

现在,environment 文件已注入到您的库中。

使用方法:

environment :any
constructor(@Inject('config') config) 
{         
     if (config) {
     this.environment = config;
   } 
}

现在可以轻松地从主项目更改环境。

【讨论】:

  • 我已经开始工作了。我的问题是,我不想导入主项目中的所有库模块。而是导入一个父模块,将环境传递给父模块,父模块必须将环境传递给它的子模块。这是我的实际需要。
  • 使用服务为您提供环境,然后将其注入您想要的任何地方,我认为这可能会解决您的问题,模块只是名称空间,在这种情况下限制功能可能会导致问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 2019-06-14
  • 1970-01-01
  • 2015-08-02
  • 2021-01-18
  • 1970-01-01
  • 2020-03-23
相关资源
最近更新 更多