<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Danila Egorenko</title>
    <description>The latest articles on DEV Community by Danila Egorenko (@danilaegorenko).</description>
    <link>https://dev.to/danilaegorenko</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1190926%2Fcc4d9b8d-cebc-468b-801c-bb41ba4b6fbb.jpeg</url>
      <title>DEV Community: Danila Egorenko</title>
      <link>https://dev.to/danilaegorenko</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/danilaegorenko"/>
    <language>en</language>
    <item>
      <title>Dependency Injection in Angular in simple words</title>
      <dc:creator>Danila Egorenko</dc:creator>
      <pubDate>Sat, 21 Oct 2023 19:02:32 +0000</pubDate>
      <link>https://dev.to/danilaegorenko/dependency-injection-in-angular-in-simple-words-3nnf</link>
      <guid>https://dev.to/danilaegorenko/dependency-injection-in-angular-in-simple-words-3nnf</guid>
      <description>&lt;p&gt;Hello everyone👋 My name is Danila, Angular front-end developer. I started learning Angular not so long ago, so I often come across complex topics that are incomprehensible and need to be analyzed. One of these topics was Dependency Injection. Well, let's figure it out :)&lt;/p&gt;

&lt;h2&gt;
  
  
  A few words about DI
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Dependency injection, or DI, is a design pattern and mechanism for reusing code across different parts of an application.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A simple example is tea with sugar. We have tea, but without sugar it is not as tasty as with it. To get a tasty drink, we take a teaspoon (injector), add sugar (addiction) from the sugar bowl (provider) and put it in a mug.&lt;/p&gt;

&lt;h2&gt;
  
  
  Services
&lt;/h2&gt;

&lt;p&gt;The most common dependency in Angular is services, but there can be other meanings as well.&lt;/p&gt;

&lt;p&gt;A service in Angular is created like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Injectable({ // Decorator that tells DI that this class can be injected
   providedIn: 'root'
})
class Service {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The provideIn property specifies where exactly to inject. Its available values:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;root&lt;/code&gt; - to the root upon request&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;platform&lt;/code&gt; - allows you to use the service in two or more root components (microservices, widgets)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;any&lt;/code&gt; - in each area of implementation (that is, in regular modules, the instance will be common, but in lazy modules, each will have its own. P.S. will be removed in version 17)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's imagine that we have 10 services, but we only use 2 on the page. Then, thanks to dependency injection, we will not call 8 unused services. This will reduce the package size and resource consumption.&lt;/p&gt;

&lt;h2&gt;
  
  
  Injectors need providers
&lt;/h2&gt;

&lt;p&gt;Injectors look for dependencies, and providers provide them.&lt;/p&gt;

&lt;p&gt;The easiest way to specify a provider:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;providers: [Service] // where, Service is a dependency
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This entry can be interpreted as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;providers: [{ provide: Service, useClass: Service }]
// where, provide (token) is the key to search for the dependency,
// and useClass - creates an instance of the class when implemented
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  And now we implement
&lt;/h2&gt;

&lt;p&gt;Well, DI is sorted out. What's next? Dependency injection uses Injector and its hierarchies. Let's look at his work:&lt;/p&gt;

&lt;p&gt;Angular has 2 types of teaspoon injectors: &lt;code&gt;ModuleInjector&lt;/code&gt; (created explicitly and used in modules and &lt;code&gt;@Injectable()&lt;/code&gt;) and &lt;code&gt;ElementInjector&lt;/code&gt; (created implicitly in every DOM element with an empty value, configured in component and directive providers).&lt;/p&gt;

&lt;p&gt;When you create an &lt;code&gt;ElementInjector&lt;/code&gt; in the directive/component constructor, it appears in the lexical environment and when further requested, Angular will look for it from your current module (for example, a page), going up the hierarchy until it reaches the highest one - &lt;code&gt;@NullInjector()&lt;/code&gt;, which always throws an error (unless you use the &lt;code&gt;@Optional()&lt;/code&gt; modifier).&lt;/p&gt;

&lt;h2&gt;
  
  
  Modifiers
&lt;/h2&gt;

&lt;p&gt;When we create a component/directive, we get the dependencies in the class constructor. Thanks to modifiers, you can determine the visibility or way of creating instances:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;constructor(@Optional() service: Service) {}&lt;/code&gt;&lt;br&gt;
There are 4 types:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;@Optional()&lt;/code&gt; - optional dependency (used when it is not known whether there will be a dependency or not)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;@Self()&lt;/code&gt; - looks for a dependency locally in a module&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;@SkipSelf()&lt;/code&gt; - searches for dependency starting from the parent element (scope)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;@Host()&lt;/code&gt; - indicates that if the DI mechanism has reached the host, then the dependency search should be stopped&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If necessary, they can be mixed. But not all, you cannot mix &lt;code&gt;@Host()&lt;/code&gt; and &lt;code&gt;@Self()&lt;/code&gt;, as well as &lt;code&gt;@SkipSelf()&lt;/code&gt; and &lt;code&gt;@Self()&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  Properties use*
&lt;/h2&gt;

&lt;p&gt;There are 4 methods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;useClass&lt;/code&gt; - as I wrote earlier, creates an instance of a class&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;useExisting&lt;/code&gt; - unlike its predecessor, uses an already created instance (useful for singletons, when one instance is used throughout the application)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;useFactory&lt;/code&gt; - uses a function to inject a dependency (convenient for overriding logic, for example, passing a service as function arguments, obtaining information from the service and using it in the constructor)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;useValue&lt;/code&gt; - allows you to use any value as a dependency&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  What if we implement something other than a class?
&lt;/h2&gt;

&lt;p&gt;For such cases there is InjectionToken. It can be used, for example, to transfer config in an application.&lt;/p&gt;

&lt;p&gt;It is created like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { InjectionToken } from '@angular/core';

const drink = new InjectionToken&amp;lt;string&amp;gt;('Drink')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And it is used like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;providers: [{ provide: drink, useValue: 'Tea' }]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What if you need an array of dependencies?
&lt;/h2&gt;

&lt;p&gt;If an array is required instead of one dependency, then the multi property is used. Then the values will not be overwritten, but the values will be added to the array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;providers: [
   { provide: drink, useValue: 'Tea', multi: true },
   { provide: drink, useValue: 'Water', multi: true },
]
export class drinkComponent implements OnInit {
   constructor(arr: drink) {}

   ngOnInit() {
     console.log(this.arr); // ['Tea', 'Water']
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I hope this article will help you better understand how dependency injection works :)&lt;/p&gt;

&lt;p&gt;And, of course, good luck to everyone in learning such a beast as Angular😉&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
