Home Web Front-end JS Tutorial An in-depth analysis of dependency injection in Angular

An in-depth analysis of dependency injection in Angular

Sep 08, 2021 am 11:06 AM
angular dependency injection

What is dependency injection? This article will take you through dependency injection in Angular, I hope it will be helpful to you!

An in-depth analysis of dependency injection in Angular

Dependency injection concept:

Wikipedia’s explanation of dependency injection: In software engineering, Dependency injection is a software design pattern that implements inversion of control. A dependency is an object (service) called by another object (client). Injection is to pass the dependent object (service) instance to the dependent object (client). the behavior of.

It is the basic principle of DI to pass the dependent objects to the dependents without requiring the dependents to create or find the required objects themselves.

Dependency injection allows programming to follow the principle of dependency inversion (simply put, it requires programming the abstraction, not the implementation, thus reducing the coupling between the client and the implementation module). The caller (client) only It is necessary to know the interface of the service. The search and creation of specific services are handled by the injector and provided to the client. This separates the dependence of the service and the caller and complies with the low-coupling programming principle. It is also the main purpose of dependency injection. [Related tutorial recommendations: "angular tutorial"]

Inversion of control

Inversion of control and dependency injection are complementary to each other. Example: classA depends on classB but classA does not actively create an instance of classB and passes it in as a parameter.

class A {
    construct(private b: B) {}
}
class B {}
const a: A = new A(new B());
Copy after login

Angular dependency injection is when instantiating a component, passing in the service instance, forming an inversion of control.

Dependency Injection

Angular dependency injection uses an instance, which is also a way for Angular to communicate through services. If dependency injection is not applied, multiple instances and inter-component communication will not be able to use services. app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, InjectionToken } from '@angular/core';
import { AppComponent } from './components/app/app.component';
import { SingleServiceService } from './service/single-service.service';
import { MyServiceService } from './service/my-service.service';
import { UseServiceService } from './service/use-service.service';
import { ValueServiceService } from './service/value-service.service';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

export interface AppConfig {
    title: string
}

export const CONFIG = new InjectionToken<AppConfig>(&#39;描述令牌的用途&#39;);

const USE_Config = {
    title: "非类的注入令牌"
}

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        HttpClientModule,
        FormsModule,
        ReactiveFormsModule
    ],
    providers: [
        SingleServiceService,
        // 完整形式
        // {provide: SingleServiceService, useClass: SingleServiceService}
        // provide 属性存有令牌,它作为一个 key,在定位依赖值和配置注入器时使用。
        // 属性二通知如何创建依赖,实际依赖的值可以是useClass、 useExisting、useValue 或 useFactory
        // useExisting起别名,依赖注入也可以注入组件
        {provide: MyServiceService, useClass: UseServiceService},
        // useValue可以是字符串,对象等
        {provide: ValueServiceService, useValue: "依赖注入字符"},
        // 使用 InjectionToken 对象来为非类的依赖选择一个提供者令牌
        { provide: CONFIG, useValue: USE_Config }
    ],
    bootstrap: [AppComponent],
    entryComponents: []
})
export class AppModule { }
Copy after login

SingleServiceService:

import { Injectable } from &#39;@angular/core&#39;;

@Injectable()
export class SingleServiceService {

constructor() { }

}
Copy after login

MyServiceService:

import { Injectable } from &#39;@angular/core&#39;;

@Injectable()
export class MyServiceService {

    constructor() { }

    getName(): string {
        return "my-service";
    }
    
}
Copy after login

UseServiceService:

import { Injectable } from &#39;@angular/core&#39;;

@Injectable()
export class UseServiceService {

    constructor() { }

    getName(): string {
        return "use-service";
    }

}
Copy after login

ValueServiceService:

import { Injectable } from &#39;@angular/core&#39;;

@Injectable()
export class ValueServiceService {

constructor() { }

}
Copy after login

More For more programming related knowledge, please visit: programming video! !

The above is the detailed content of An in-depth analysis of 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

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

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

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

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

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

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.

What should I do if the project is too big? How to split Angular projects reasonably? What should I do if the project is too big? How to split Angular projects reasonably? Jul 26, 2022 pm 07:18 PM

The Angular project is too large, how to split it reasonably? The following article will introduce to you how to reasonably split Angular projects. I hope it will be helpful to you!

Let's talk about how to obtain data in advance in Angular Route Let's talk about how to obtain data in advance in Angular Route Jul 13, 2022 pm 08:00 PM

How to get data in advance in Angular Route? The following article will introduce to you how to obtain data in advance from Angular Route. I hope it will be helpful to you!

See all articles