VSO*_*VSO 2 angular-module angular angular-library
我正在构建一个 Angular 库,它将公开服务和中间件,以便在导入其他 Angular 应用程序时执行身份验证。
在尝试将此模块拉入独立的Angular Library之前,它依赖于environment.ts应用程序中的文件(我只是像这样导入它import { environment } from '../../../environments/environment';:)。
如何将环境文件传递到现在将导入到我的 Angular 应用程序中的模块?
environment或者将文件作为 JSON 传递给我公开的每个服务和中间件是否更好?
实现这一目标的最佳方法是为您的模块公开一个配置对象,而不是直接使用环境文件。就像是:
import { InjectionToken } from '@angular/core';
export interface LibConfig {
foo: string;
bar: string;
}
export const LibConfigService = new InjectionToken<LibConfig>('LibConfig');
Run Code Online (Sandbox Code Playgroud)
在你的主模块中:
export class LibModule {
static forRoot(config: LibConfig): ModuleWithProviders {
return {
ngModule: LibModule,
providers: [
{
provide: LibConfigService,
useValue: config
}
]
};
}
}
Run Code Online (Sandbox Code Playgroud)
因此,将库添加到项目的模块导入中时,您可以执行以下操作:
LibModule.forRoot({
foo: environment.foo,
bar: environment.bar
})
Run Code Online (Sandbox Code Playgroud)
在库中,您可以使用以下方式访问配置:
private libConfig: LibConfig;
constructor(@Inject(LibConfigService) private config) {
this.libConfig = config;
}
public getConfig(): LibConfig {
return this.libConfig;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3214 次 |
| 最近记录: |