Let's learn about dependency injection in Angular
This article will introduce you to dependency injection in Angular. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related recommendations: "angular tutorial"
Dependency injection: design pattern
Dependencies: required in the program The object of some type.
Dependency Injection Framework: Engineering Framework
Injector: Use its API to create instances of dependencies
Provider: How create? (Constructor, engineering function)
Object: dependencies required by components and modules
Advanced dependency injection=>The dependency injection framework in Angular provides parent-child hierarchical injection Type dependency
1. Dependency injection
class Id { static getInstance(type: string): Id { return new Id(); } } class Address { constructor(provice, city, district, street) {} } class Person { id: Id; address: Address; constructor() { this.id = Id.getInstance("idcard"); this.address = new Address("北京", "背景", "朝阳区", "xx街道"); } }
Problem: Person needs to clearly know the implementation details of Address and Id.
After the ID and Address are reconstructed, Person needs to know how to reconstruct them.
After the scale of the project is expanded, integration problems are prone to occur.
class Id { static getInstance(type: string): Id { return new Id(); } } class Address { constructor(provice, city, district, street) {} } class Person { id: Id; address: Address; constructor(id: Id, address: Address) { this.id = id; this.address = address; } } main(){ //把构造依赖对象,推到上一级,推调用的地方 const id = Id.getInstance("idcard"); const address = new Address("北京", "背景", "朝阳区", "xx街道"); const person = new Person(id , address); }
Person no longer knows the details of Id and Address.
This is the simplest dependency injection.
Is the problem in main or I need to know the details.
Idea: Push up one level at a time, all the way to the entry function, which handles the construction of all objects. A subclass that is constructed and provided to all dependent submodules.
Problem: Entry functions are difficult to maintain. So a dependency injection framework is needed to help complete this.
2. Angular’s dependency injection framework
Starting from v5, it has been deprecated due to its slow speed and the introduction of a large amount of code. Changed forInjector.create.
ReflectiveInjector : Used to instantiate objects and resolve dependencies.
import { Component ,ReflectiveInjector } from "@angular/core";
resolveAndCreate receives a provider array, and the provider tells the injector how to construct the object.
constructor() { //接收一个provider数组 const injector = ReflectiveInjector.resolveAndCreate([ { provide: Person, useClass:Person }, { provide: Address, useFactory: ()=>{ if(environment.production){ return new Address("北京", "背景", "朝阳区", "xx街道xx号"); }else{ return new Address("西藏", "拉萨", "xx区", "xx街道xx号"); } } }, { provide: Id, useFactory:()=>{ return Id.getInstance('idcard'); } } ]); }
Injector:
injector is equivalent to the main function and can get all the things in the dependency pool.
import { Component ,ReflectiveInjector, Inject} from "@angular/core"; import { OverlayContainer } from "@angular/cdk/overlay"; import { Identifiers } from "@angular/compiler"; import { stagger } from "@angular/animations"; import { environment } from 'src/environments/environment'; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"] }) export class AppComponent { constructor(private oc: OverlayContainer) { //接收一个provider数组 const injector = ReflectiveInjector.resolveAndCreate([ { provide: Person, useClass:Person }, { provide: Address, useFactory: ()=>{ if(environment.production){ return new Address("北京", "背景", "朝阳区", "xx街道xx号"); }else{ return new Address("西藏", "拉萨", "xx区", "xx街道xx号"); } } }, { provide: Id, useFactory:()=>{ return Id.getInstance('idcard'); } } ]); const person = injector.get(Person); console.log(JSON.stringify(person)); } } class Id { static getInstance(type: string): Id { return new Id(); } } class Address { provice:string; city:string; district:string; street:string; constructor(provice, city, district, street) { this.provice=provice; this.city=city; this.district=district; this.street=street; } } class Person { id: Id; address: Address; constructor(@Inject(Id) id, @Inject(Address )address) { this.id = id; this.address = address; } }
You can see the person information printed out on the console.
// { // provide: Person, useClass:Person // }, Person, //简写为Person
@NgModule({ imports: [HttpClientModule, SharedModule, AppRoutingModule, BrowserAnimationsModule], declarations: [components], exports: [components, AppRoutingModule, BrowserAnimationsModule], providers:[ {provide:'BASE_CONFIG',useValue:'http://localhost:3000'} ] })
constructor( @Inject('BASE_CONFIG') config) { console.log(config); //控制台打印出http://localhost:3000 }
{ provide: Address, useFactory: ()=>{ return ()=>{ if(environment.production){ return new Address("北京", "背景", "朝阳区", "xx街道xx号"); }else{ return new Address("西藏", "拉萨", "xx区", "xx街道xx号"); } } } },
constructor(private oc: OverlayContainer) { //接收一个provider数组 const injector = ReflectiveInjector.resolveAndCreate([ Person, { provide: Address, useFactory: ()=>{ if(environment.production){ return new Address("北京", "背景", "朝阳区", "xx街道xx号"); }else{ return new Address("西藏", "拉萨", "xx区", "xx街道xx号"); } } }, { provide: Id, useFactory:()=>{ return Id.getInstance('idcard'); } } ]); const childInjector = injector.resolveAndCreateChild([Person]); const person = injector.get(Person); console.log(JSON.stringify(person)); const personFromChild = childInjector.get(Person); console.log(person===personFromChild); //false }
3. Injector
This article is reproduced from: https://www.cnblogs.com/starof/p/10506295.htmlProgramming Teaching! !
The above is the detailed content of Let's learn about dependency injection in Angular. For more information, please follow other related articles on the PHP Chinese website!

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

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

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

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

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!

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!

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.

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!

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!
