Angular Dependence Injection

Hey guys it was been pretty decent journey working with angular and helping you guys out with some of the gotcha in angular.
So coming straight toward the topic "what is dependency injection in angular.
this looks pretty difficult while we encounter during reading the angular docs but this term says dependency that should be injected from other source so what is dependency for an component ? mostly we use some dependency where we are are dependent on some other component, let me take an example
let's say I have a scenario where there is two component and some data which is used to be in-sync as I have already discussed the way we are using to share the data where one component is updating and we want both of the component should be in sync with that data so here I am using services mostly in angular 2 dependency injection uses services, their services act as a single source of truth and we use constructor to inject our services in both of the component while any changes in one component should be reflected to the other component based on the subscription.
In other words we are delegating the task of subscribing the variable and pulling the variable from another component, this task to the service and we are now dependent on service to help me out with the syncing data instead of doing it own so why we do this?
we have done this mostly because we want our code should be modular and testable so that we can test both my service as well as my working component. You must have heard of solid principle where 's' stands for single responsibility so this dependency injection are there is the rule of single responsibility and my component should not be responsible for making sink of the data. we are basically delegating this to service.




so that's it for now and I hope you guys have cleared with this terminology and thank you so much for reading.

Popular Posts