A step-by-step guide to understanding dependency injection in Angular
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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment