I'm writing an Angular library named libModule where I need to pass in a configuration object in the .forRoot() of the module import.
I'm trying to do this with InjectionToken, but when I run my application(installed libModule build with ng-packagr) with ng build--prod
, I got an error just like this
ERROR in Error during template compile of 'TestModule' Function calls are not supported in decorators but 'libModule' was called.
libModule
import { NgModule } from '@angular/core';
import { CONFIG, Config } from './config';
import { LibService } from './libService';
@NgModule({ ... })
export class LibModule {
static forRoot(config?: any): ModuleWithProviders {
return {
ngModule: LibModule,
providers: [
LibService,
{ provide: CONFIG, useValue: config }
]
};
}
}
config.ts
import { InjectionToken } from '@angular/core';
export const CONFIG = new InjectionToken<Config>('config');
export interface Config {
key?: string;
}
libService.ts
import { Observable } from "rxjs/Observable";
import { Injectable, Inject } from "@angular/core";
import { Config, LIB_CONFIG } from "./config";
@Injectable()
export class LibService {
private key: string;
constructor(
@Inject(LIB_CONFIG) config: any
) {
this.key = config.KEY;
console.log('ewrwerwerwrewrewr'+this.key);
}
}
consume application TestModule
import { NgModule } from '@angular/core';
import { LibModule } from 'some-library';
@NgModule({
imports: [
libModule.forRoot({
// <-- config values here
})
]
})