Angular Dependency Injection
Posted By : Damandeep Singh | 27-Jun-2018
Let's take an example before writing the definition:
Assume we have three classes as Class A, Class B, Class C. Class A implements
Now one way is to create an instance of class B and Class C and then we can easily use it. this method we have applied in C++ and other languages.
But if we consider the memory and time as the main perspective then this code is a failure because if we have 'n' number of classes using the
'n' memory spaces will be created because every time we create a new object, new memory gets allocated and it will consume a lot of time too. Also, there will be no sharing between these classes.
And one More Problem like if we add a new argument to the function then at the time of instance creation we have to add that argument in the instance call else the code fails so it's very difficult to maintain the code.
Angular Provides Dependency Injection for solving these problems of time, memory, sharing, and maintenance.
We create a class A (service class ) and then we mention that service class in providers either at module level or Component Level. Because with the help of
Then in the constructor, we declare a private variable of service class type which creates an instance for the service class only once the service gets started. Also if we make any changes in the service class then the instance is overridden instead of creating again.
So basically,
- Dependency injection is a coding pattern in which a class receives its dependencies from any other source rather than creating it themselves.
- With this we do not need to create an instance of the service, instance gets created by the injector automatically.
- Also, this helps in creating singleton service that is one service class gets called by 'n' number of classes by creating a single instance for the service class.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Damandeep Singh
Damandeep Singh is a Front-end Developer having Good knowledge of HTML, CSS3/CSS, Bootstrap, Angular, Ionic. He likes to listen to Music in Free time.