Last active
November 10, 2021 08:37
-
-
Save peplocanto/8515c563fc4e988a3ab5a8c5bd51a273 to your computer and use it in GitHub Desktop.
This file contains 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
// best practice arch | |
// app | |
// L core | |
// L core.module.ts | |
// L core.providers.ts | |
// L core.model.ts | |
// core.module.ts | |
import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core'; | |
import { CoreConfigurationContract, CORE_CONFIGURATION } from '@core/core.model'; | |
import { APP_INITIALIZER_PROVIDERS } from '@core/core.providers'; | |
const MODULES = []; | |
const INNER_COMPONENTS = []; | |
const OUTER_COMPONENTS = []; | |
@NgModule({ | |
imports: [...MODULES], | |
declarations: [...INNER_COMPONENTS, ...OUTER_COMPONENTS], | |
exports: [...OUTER_COMPONENTS] | |
}) | |
export class CoreModule { | |
constructor(@Optional() @SkipSelf() parentModule: CoreModule) { | |
if (!!parentModule) { | |
console.error('"CoreModule" already loaded. Import it _ONLY_ on main "AppRootModule".'); | |
} | |
} | |
static forRoot(coreConfigurationFactory: () => CoreConfigurationContract): ModuleWithProviders { | |
return { | |
ngModule: CoreModule, | |
providers: [ | |
{ provide: CORE_CONFIGURATION, useFactory: coreConfigurationFactory }, | |
...APP_INITIALIZER_PROVIDERS | |
] | |
}; | |
} | |
} | |
// core.providers.ts | |
import { APP_INITIALIZER, Provider } from '@angular/core'; | |
export const load<Name>ServiceFnFactory = (<name>Service: <Name>Service): (() => Promise<any>) => () => { | |
<name>Service.init(); | |
return Promise.resolve(); | |
/* | |
or | |
<name>Service.init().pipe().subscribe(() => Promise.resolve()) | |
*/ | |
}; | |
export const APP_INITIALIZER_PROVIDERS: Provider[] = [ | |
{ | |
provide: APP_INITIALIZER, | |
useFactory: load<Name>ServiceFnFactory, | |
deps: [<Name>Service], | |
multi: true | |
} | |
]; | |
// core.model.ts | |
export interface CoreConfigurationContract {} | |
export const CORE_CONFIGURATION = new InjectionToken<CoreConfigurationContract>('<DOMAIN>_CORE_CONFIGURATION_TOKEN'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment