亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
What is Dependency Injection
Angular's DI framework
Injector injector
總結(jié)
Home Web Front-end JS Tutorial A step-by-step guide to understanding dependency injection in Angular

A step-by-step guide to understanding dependency injection in Angular

Dec 02, 2022 pm 09:14 PM
angular angular.js dependency injection

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!

A step-by-step guide to understanding dependency injection in Angular

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"
//服務(wù)類
class Video{}
//創(chuàng)建注入器并傳入服務(wù)類
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ù),但是在子級注入器實(shí)例化的時候,由于自身不存在 Video 這個服務(wù),它就會去父級查找,當(dāng)然,就找到了父級的 Video 這個服務(wù)并且實(shí)例化,所以后面的兩個實(shí)例化對象相等

總結(jié)

本文介紹了依賴注入解決的問題和它原生的寫法是什么用的,并且介紹了Angular提供給我們的DI框架,用它提供給我們的簡單api實(shí)現(xiàn)了實(shí)例化的過程,并且講解了注入器,也是會分層級的,能提供給我們更好地一個項(xiàng)目設(shè)計(jì)方式。之后有機(jī)會再來講解一下provider以及更多的擴(kuò)展。

更多編程相關(guān)知識,請?jiān)L問:編程視頻?。?/p>

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

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

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

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

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

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

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

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.

How to use dependency injection (Dependency Injection) in the Phalcon framework How to use dependency injection (Dependency Injection) in the Phalcon framework Jul 30, 2023 pm 09:03 PM

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

Go Language: Dependency Injection Guide Go Language: Dependency Injection Guide Apr 07, 2024 pm 12:33 PM

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.

Dependency injection using JUnit unit testing framework Dependency injection using JUnit unit testing framework Apr 19, 2024 am 08:42 AM

For testing dependency injection using JUnit, the summary is as follows: Use mock objects to create dependencies: @Mock annotation can create mock objects of dependencies. Set test data: The @Before method runs before each test method and is used to set test data. Configure mock behavior: The Mockito.when() method configures the expected behavior of the mock object. Verify results: assertEquals() asserts to check whether the actual results match the expected values. Practical application: You can use a dependency injection framework (such as Spring Framework) to inject dependencies, and verify the correctness of the injection and the normal operation of the code through JUnit unit testing.

Explain the concept of Dependency Injection (DI) in PHP. Explain the concept of Dependency Injection (DI) in PHP. Apr 05, 2025 am 12:07 AM

The core value of using dependency injection (DI) in PHP lies in the implementation of a loosely coupled system architecture. DI reduces direct dependencies between classes by providing dependencies externally, improving code testability and flexibility. When using DI, you can inject dependencies through constructors, set-point methods, or interfaces, and manage object lifecycles and dependencies in combination with IoC containers.

See all articles