Last active
September 6, 2022 07:22
-
-
Save hakimio/ad655f8e91dc759d172ea0a99a0df99a to your computer and use it in GitHub Desktop.
Global App Injector in Angular below v14
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 {Injector} from '@angular/core'; | |
| export class AppInjector { | |
| private static injector: Injector; | |
| static setInjector(injector: Injector) { | |
| AppInjector.injector = injector; | |
| } | |
| static getInjector(): Injector { | |
| return AppInjector.injector; | |
| } | |
| } |
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
| export function getService<T>(serviceType: Type<T>): T { | |
| const injector = AppInjector.getInjector(); | |
| return injector.get(type); | |
| } |
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
| platformBrowserDynamic() | |
| .bootstrapModule(AppModule) | |
| .then( | |
| (moduleRef) => { | |
| AppInjector.setInjector(moduleRef.injector); | |
| } | |
| ) | |
| .catch(err => console.log(err)); |
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
| this.reportService = getService(ReportService); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment