This 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{} //创建注入器并传入服务类 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
像上面这段代码,我们在创建子级注入器的时候,不传递参数,但是在子级注入器实例化的时候,由于自身不存在 Video 这个服务,它就会去父级查找,当然,就找到了父级的 Video 这个服务并且实例化,所以后面的两个实例化对象相等
总结
本文介绍了依赖注入解决的问题和它原生的写法是什么用的,并且介绍了Angular提供给我们的DI框架,用它提供给我们的简单api实现了实例化的过程,并且讲解了注入器,也是会分层级的,能提供给我们更好地一个项目设计方式。之后有机会再来讲解一下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!

本篇文章带大家继续angular的学习,简单了解一下Angular中的独立组件(Standalone Component),希望对大家有所帮助!

本篇文章带大家深入了解一下angular的状态管理器NgRx,介绍一下NgRx的使用方法,希望对大家有所帮助!

Angular项目过大,怎么合理拆分它?下面本篇文章给大家介绍一下合理拆分Angular项目的方法,希望对大家有所帮助!

怎么自定义angular-datetime-picker格式?下面本篇文章聊聊自定义格式的方法,希望对大家有所帮助!

本篇文章带大家了解一下Angular中的独立组件,看看怎么在Angular中创建一个独立组件,怎么在独立组件中导入已有的模块,希望对大家有所帮助!

本篇文章带大家了解一下依赖注入,介绍一下依赖注入解决的问题和它原生的写法是什么,并聊聊Angular的依赖注入框架,希望对大家有所帮助!

本篇文章带大家深入了解一下angular中的几个特殊选择器:host、:host-context、::ng-deep,希望对大家有所帮助!

Component是Directive的子类,它是一个装饰器,用于把某个类标记为Angular组件。下面本篇文章就来带大家深入了解angular中的@Component装饰器,希望对大家有所帮助。


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
