Created
October 12, 2020 13:53
-
-
Save vijayksingh/6b424ae840d6aa5a1342e3ba5827e309 to your computer and use it in GitHub Desktop.
A simple implementation of Dependency Injection in Angular
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
| class UserService { | |
| sayHi() { | |
| console.log('hi'); | |
| } | |
| } | |
| class Component { | |
| constructor(private user: UserService) {} | |
| } | |
| class Injector { | |
| private _container = new Map(); | |
| constructor(private _providers: any[] = []) { | |
| this._providers.forEach((service) => | |
| this._container.set(service, new service()) | |
| ); | |
| } | |
| get(service: any) { | |
| const serviceInstance = this._container.get(service); | |
| if (!serviceInstance) { | |
| throw Error('No Provider found'); | |
| } | |
| return serviceInstance; | |
| } | |
| } | |
| const injector = new Injector([UserService]); | |
| const component = new Component(injector.get(UserService)); | |
| component.user.sayHi(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment