Angular2 providing configuration to a library

354 Views Asked by At

I am writing a library service for Angular 2 and I wish for the calling application to be able to supply some configuration. I could make abstract properties on the base classes, but this would lead to a lot the calling application having to define the configuration in multiple places.

Within Angular2 applications I use a technique like this in the main application module

let config: any = { param1: 'value 1', param2: 'value 2' };

@NgModule({
    providers: [ {provide: 'app.config', useValue: config } ]
})

I can then inject the config where needed with @Inject('app.config') . However, as the library I am writing is defining base classes to be extended I don't want to have this value injected on the constructor as it would require the calling application to inject the value and forward it via super().

I've been looking at the ReflectiveInjector class, but it wants a type rather than a string.

    let appConfig = ReflectiveInjector.resolve('app.config').get();

How can I achieve this?

2

There are 2 best solutions below

1
On

I've been looking at the ReflectiveInjector class, but it wants a type rather than a string.

Something like this?

let config: any = { param1: 'value 1', param2: 'value 2' };

let injector: any = ReflectiveInjector.resolveAndCreate([
  {
    provide: 'app.config',
    useValue: config
  }
]);

let configService = injector.get('app.config');

console.log(configService);
6
On

You can define an OpaqueToken

export const APP_CONFIG = new OpaqueToken('app.config');

And use it as a type, instead of using a string

let appConfig = ReflectiveInjector.resolve(APP_CONFIG).get();

If I understood correctly, you want to load some configuration data with a single request before the application initializes, and keep it in a singleton. I strongly recommend you having a look at the post #37611549, as it explains use of APP_INITIALIZER - to execute a function when the app is initialized and delay what it provides if the function returns a promise.