Last active
January 21, 2020 05:32
-
-
Save roalcantara/83ee80dae7da685a258a693bbd704b92 to your computer and use it in GitHub Desktop.
[Angular 8] Module.forRoot() configuration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { FooModule } from "@foo/modules" | |
import { config } from "@foo/config" | |
@NgModule( { | |
imports: [ | |
BrowserModule, | |
FooModule.forRoot(config) | |
] | |
bootstrap: [ AppComponent ], | |
}) | |
export class AppModule {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { InjectionToken, ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core' | |
import { FooService } from '@foo/services' | |
export type AppConfig = { apiKey: string; databaseURL: string } | |
export const APP_CONFIG = new InjectionToken<string>('APP_CONFIG') | |
// Fix the AoT` error "Consider changing the function expression into an exported function" | |
export function buildApp(config: AppConfig) { | |
return new FooService(config) | |
} | |
@NgModule() | |
export class FooModule { | |
static forRoot(config: AppConfig): ModuleWithProviders { | |
return { | |
ngModule: FooModule, | |
providers: [ | |
{ provide: APP_CONFIG, useValue: config }, | |
{ | |
provide: FooService, | |
useFactory: buildApp, | |
deps: [APP_CONFIG] | |
} | |
] | |
} | |
} | |
constructor(@Optional() @SkipSelf() parentModule: FooModule) { | |
if (parentModule) { | |
throw new Error('FooModule is already loaded. Import it in the AppModule only') | |
} | |
} | |
} | |
// References: | |
// https://angular.io/guide/singleton-services#the-forroot-pattern | |
// https://angular.io/guide/singleton-services#prevent-reimport-of-the-greetingmodule | |
// https://github.com/angular/angular/issues/33539 | |
// https://www.bennadel.com/blog/3565-providing-module-configuration-using-forroot-and-ahead-of-time-compiling-in-angular-7-2-0.htm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment