


A step-by-step guide to understanding dependency injection in Angular
Dec 02, 2022 pm 09:14 PMThis article will take you to understand dependency injection, introduce the problems solved by dependency injection and its native writing method, and talk about the dependency injection framework of Angular. I hope it will be helpful to everyone!
Recently, I often come across the keyword dependency injection in Angular projects, but I still don’t understand how it is implemented. On Angular’s ??official website, there is only Regarding its use, the detailed principles are not explained, so let's explain it from the native writing method, what problems dependency injection is used to solve, and how it should be expressed using js. [Related tutorial recommendations: "angular tutorial"]
What is Dependency Injection
Dependency injection, referred to as DI, is a design principle in object-oriented programming. Reduce coupling between codes.
Let’s look at a piece of code first
class Video{ constructor(url){} } class Note{ video: Video constructor(){ this.video = new Video("https://aaaaa.mp4") } getScreenshot(){ this.video.getScreenshot() } } const note = new Note() note.getScreenshot()
Suppose we use a video class, which has a method getScreenshot to obtain screenshots. When instantiating the video class, a video url needs to be passed in like this parameters. Now there is a note class, which needs to call the screenshot method under the video class. Then we can say that the note class depends on the video class. So inside the note class, we need to instantiate the video class, so that we can get the instance object of the video class in the note class and call the screenshot method in it.
The coupling of the above code is too high and is not recommended. For example, if the video address of the Video is changed, then the incoming video URL needs to be changed in Note. This assumes that if there are more The class depends on the video class, so once a change is made, everything must be changed accordingly, which is very inconvenient.
Next, we use dependency injection to solve the above problem:
class Note{ video: Video constructor(video: Video){ this.video = Video; } } const video = new Video("https://aaaaa.mp4") const note = new Note(video)
We instantiate the video class outside the class, and pass the instance to the note class through parameter passing. Through this This method can successfully solve the problem of excessive coupling. We call this method of passing instances through parameters: injection.
Advantages
Dependency injection reduces the coupling between codes and increases the maintainability of the code. Code changes in the video class will not affect the note class.
Angular's DI framework
In the above implementation process, there is still one thing that is not particularly ideal, that is, we need to instantiate the video class outside the class, although this is the only one , but we still hope that no matter how the internal changes of the video class are changed, the external code will not be affected.
In the DI framework provided by Angular, we do not need to instantiate the video class ourselves. It hides the process of implementing dependency injection. For developers, they only need to use a very simple The code can then use sophisticated dependency injection functionality.
There are four core concepts in Angular's DI:
Dependency: the instance object that the component depends on, the service instance object
-
Token: Get the identifier of the service instance object. Angular will maintain many instance objects. When we need to obtain it, we need to obtain it through the identifier.
Injector: Injector , responsible for creating and maintaining instance objects of service classes, injecting service instance objects into components, and passing them to each component through parameters
Procider: object, used to configure the injector, specify Create the service class of the service instance object and obtain the identifier of the instance object
Injector injector
We first create an injector through the basic syntax provided by Angular
1. Create an injector
import { ReflectiveInjector } from "@angular/core" //服務類 class Video{} //創(chuàng)建注入器并傳入服務類 const injector = ReflectiveInjector.resolveAndCreate([ Video ])
Introduce ReflectiveInjector and the resolveAndCreate method is used to create an injector. It receives an array. In the array is the class that needs to create an instance object. This method will return an injector. 2. Get the service class instance object in the injector
const video = injector.get(Video)
There is a get method under the injector, which is used to pass in the identifier and get the instance object. The default identifier is the name of the service class, which is Video
In this way, we can get the instance object of Video. The DI framework provided by Angular makes it unnecessary for us to manually instantiate a class to obtain its instance object. It will do it for us.
2. The instance object of the service is in singleton mode. The injector regrets caching it after creating the service instance.
const video1 = injector.get(Video) const video2 = injector.get(Video) console.log(video1 === video1)//true
In other words, no matter how many times the instance object is obtained through the framework, it returns are all the same instance object
3. However, we can create multiple injectors. The objects instantiated by the same service returned by different injectors are not the same
const injector1 = ReflectiveInjector.resolveAndCreate([ Video ]) const injector2 = ReflectiveInjector.resolveAndCreate([ Video ]) const video1 = injector1.get(Video) const video2 = injector2.get(Video) console.log(video1 === video1)//false
4. There is a method to create a child injector on the injector called resolveAndCreateChild. This method will create a child injector. The relationship between the parent injector and the child injector is similar to the scope chain of js. The current injector cannot find it. When it arrives, it will search for the parent injector, such as:
const injector = ReflectiveInjector.resolveAndCreate([ Video ]) const injectorChild = injector.resolveAndCreateChild([]) const video1 = injector.get(Video) const video2 = injectorChild.get(Video) console.log(video1 === video1)//true
像上面這段代碼,我們在創(chuàng)建子級注入器的時候,不傳遞參數(shù),但是在子級注入器實例化的時候,由于自身不存在 Video 這個服務,它就會去父級查找,當然,就找到了父級的 Video 這個服務并且實例化,所以后面的兩個實例化對象相等
總結
本文介紹了依賴注入解決的問題和它原生的寫法是什么用的,并且介紹了Angular提供給我們的DI框架,用它提供給我們的簡單api實現(xiàn)了實例化的過程,并且講解了注入器,也是會分層級的,能提供給我們更好地一個項目設計方式。之后有機會再來講解一下provider以及更多的擴展。
更多編程相關知識,請訪問:編程視頻!!
The above is the detailed content of A step-by-step guide to understanding dependency injection in Angular. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

Do you know Angular Universal? It can help the website provide better SEO support!

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

This article will take you through the method of transferring data between parent and child components (Component) in Angular. It will introduce the method of parent component transferring data to child component and child component transferring data to parent component in Angular. I hope it will be helpful to you!

Introduction to the method of using dependency injection (DependencyInjection) in the Phalcon framework: In modern software development, dependency injection (DependencyInjection) is a common design pattern aimed at improving the maintainability and testability of the code. As a fast and low-cost PHP framework, the Phalcon framework also supports the use of dependency injection to manage and organize application dependencies. This article will introduce you how to use the Phalcon framework

Answer: In Go language, dependency injection can be implemented through interfaces and structures. Define an interface that describes the behavior of dependencies. Create a structure that implements this interface. Inject dependencies through interfaces as parameters in functions. Allows easy replacement of dependencies in testing or different scenarios.
