VSO
VSO

Reputation: 12656

Pass environment.ts To Angular Library Module

I am building an Angular library which will expose a service and middleware to perform authentication when imported into other Angular apps.

Before trying to pull this module into a standalone Angular Library, it was relying on the environment.ts file in the application (I just imported it like so: import { environment } from '../../../environments/environment';).

How do I pass the environment file to a module that will now be imported into my Angular application?

Or is it better to pass the environment file, as JSON, to each service and piece of middleware I am exposing?

Upvotes: 3

Views: 3619

Answers (2)

Tiago Viegas
Tiago Viegas

Reputation: 201

You can configure a module using the forRoot pattern.

On your library module:

export const OPTIONS = new InjectionToken<LibraryOptions>('options');

@NgModule({...})
export class LibraryModule {

  static forRoot(options: LibraryOptions): ModuleWithProviders {
  return {
   ngModule: LibraryModule,
   providers: [
   {
     provide: OPTIONS,
     useValue: options
   }]
  }
 }

}

then inject OPTIONS token on your components and services to access the options.

constructor(@Inject(OPTIONS) options: LibraryOptions){}

to use the LIbrary:

imports:[LibraryModule.forRoot({...})]

Upvotes: 1

Henrique Erzinger
Henrique Erzinger

Reputation: 1147

The best way to achieve that is to expose a configuration object for you module, instead of using the environment file direct. Something like:

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

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

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

in your main module:

export class LibModule {

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

and so when adding the library to your project's module imports, you can do:

LibModule.forRoot({
  foo: environment.foo,
  bar: environment.bar
})

and in the lib, you can access the config with something like:

  private libConfig: LibConfig;

  constructor(@Inject(LibConfigService) private config) {
    this.libConfig = config;
  }

  public getConfig(): LibConfig {
    return this.libConfig;
  }

Upvotes: 8

Related Questions