Skip to content

Instantly share code, notes, and snippets.

@vijayksingh
Created October 12, 2020 13:53
Show Gist options
  • Select an option

  • Save vijayksingh/6b424ae840d6aa5a1342e3ba5827e309 to your computer and use it in GitHub Desktop.

Select an option

Save vijayksingh/6b424ae840d6aa5a1342e3ba5827e309 to your computer and use it in GitHub Desktop.
A simple implementation of Dependency Injection in Angular
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