In my application a config object that is being injected from the window to the Angular application. To go about this I had developed something along these lines:
Code
Model representing the config
export class AppConfig {
constructor(
public apiKey: string,
public username: string,
public languageCode: string
) { }
}
Creating an InjectionToken
import { InjectionToken } from '@angular/core';
import { AppConfig } from './shared';
export let APP_CONFIG = new InjectionToken<AppConfig>('appConfig');
This is then provided in the AppModule
import { APP_CONFIG } from './app-config-export';
....
@NgModule({
....
{ provide: APP_CONFIG, useValue: (window as any).appConfig }
})
export class AppModule { }
Finally inject it in a component
import { AppConfig } from '../shared';
import { APP_CONFIG} from './app-config-export';
....
export class AppComponent implements OnInit {
constructor(
@Inject(APP_CONFIG) private appConfig: any,
private appService: AppService
) { }
ngOnInit() {
this.appService.initApp(this.appConfig);
}
}
AOT Compilation
This works fine, however now I've been trying to build the application using AOT compilation. When I run the application with AOT, the appConfig
is always null
. I'm guessing it has something to do with the way I'm injecting the config which might not be compatible with AOT. Is there a way to get this to work with AOT?
I found this thread on github https://github.com/angular/angular/issues/19154, however I'm not understanding what is meant by "use a factory instead".
- Angular: 4.4.4
- Webpack: 3.8.1
Update
I've updated the AppModule like so:
import { APP_CONFIG } from './app-config-export';
....
export function appConfigFactory() {
return (window as any).appConfig;
}
@NgModule({
....
{ provide: APP_CONFIG, useFactory: appConfigFactory() }
})
export class AppModule { }
Solution
I've updated the AppModule like so:
import { APP_CONFIG } from './app-config-export';
....
export function appConfigFactory() {
return (window as any).appConfig;
}
@NgModule({
....
{ provide: APP_CONFIG, useFactory: appConfigFactory }
})
export class AppModule { }
I was calling the function in the useFactory
callback instead of passing the function.