将environment.ts传递到Angular库模块

问题描述 投票:0回答:1

我正在构建一个Angular库,当将其导入其他Angular应用程序时,它将公开服务和中间件以执行身份验证。

[在尝试将此模块放入独立的Angular Library之前,它依赖于应用程序中的environment.ts文件(我只是这样导入它:import { environment } from '../../../environments/environment';)。

如何将环境文件传递到现在将导入到Angular应用程序中的模块中?

或者将environment文件作为JSON传递给我要公开的每个服务和中间件更好吗?

angular angular-module angular-library
1个回答
0
投票

实现此目的的最佳方法是为您的模块公开一个配置对象,而不是直接使用环境文件。类似于:

import { InjectionToken } from '@angular/core';

export interface LibConfig {
  foo: string;
  bar: string;
}

export const LibConfigService = new InjectionToken<LibConfig>('LibConfig');

在您的主模块中:

export class LibModule {

  static forRoot(config: LibConfig): ModuleWithProviders {
    return {
      ngModule: LibModule,
      providers: [
        {
          provide:  LibConfigService,
          useValue: config
        }
      ]
    };
  }
}

因此在将库添加到项目的模块导入中时,您可以执行以下操作:

LibModule.forRoot({
  foo: environment.foo,
  bar: environment.bar
})
© www.soinside.com 2019 - 2024. All rights reserved.