Scope of Dependency in Angular is very important concept to understand for a full stack developer. This is primarily asked question by interviewer in many different forms.
Let’s understand the basics of this concept through our video tutorial 0008-17- angular: Injector and Provider Relationship 3/4. It explains how scope of dependency is defined at each component or module and how it serves the purpose in real world projects.
Modules, components or directives use injectors and Injector use provider to finally get the dependency. At the root node of a module if we define a provider, then its scope is entire module where it is defined. Whichever node a provider is defined, it is scoped to that node and its hierarchy. We know that component or module get Injectors at bootstrapping time. Injectors uses provider to find out any dependency. If it’s not available at its provider, it will go to its parent component and ask the dependency there with same DI token. If it gets there it will give or its goes to above hierarchy until it gets the dependency.
At any time at any node if you define another provider for the same DI token you will get new independent instance there. This makes it a very powerful concept in angular as for a list of items we can define independent instance of same service for each item. In AngularJS if we define a service it was singleton or global throughout the app, and this shortcoming was overcome through this concept in Angular 2.