Home Web Front-end JS Tutorial Let's learn about dependency injection in Angular

Let's learn about dependency injection in Angular

Feb 19, 2021 pm 05:56 PM
angular dependency injection

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.

Let's learn about dependency injection in Angular

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街道");
  }
}
Copy after login

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);
}
Copy after login

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";
Copy after login

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');
        }
      }
    ]);
  }
Copy after login

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;
  }
}
Copy after login

You can see the person information printed out on the console.

##Abbreviation:

      // {
      //   provide: Person, useClass:Person
      // },
      Person, //简写为Person
Copy after login

In the Angular framework, the framework does a lot of things. Things registered in the provider array will automatically be registered in the pool.

@NgModule({
  imports: [HttpClientModule, SharedModule, AppRoutingModule, BrowserAnimationsModule],
  declarations: [components],
  exports: [components, AppRoutingModule, BrowserAnimationsModule],
  providers:[
    {provide:'BASE_CONFIG',useValue:'http://localhost:3000'}
  ]
})
Copy after login
  constructor( @Inject('BASE_CONFIG') config) {
    console.log(config);  //控制台打印出http://localhost:3000
  }
Copy after login

Angular is a singleton by default. If you want to inject a new instance every time. There are two ways.

First, when returning, return a method instead of an object.

{
        provide: Address, useFactory: ()=>{
          return ()=>{
            if(environment.production){
              return new Address("北京", "背景", "朝阳区", "xx街道xx号");
            }else{
              return new Address("西藏", "拉萨", "xx区", "xx街道xx号");
            }
          }
        }
      },
Copy after login

2. Use the father-son Injector.

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
  }
Copy after login
When the dependency is not found in the child injector, it will look for it in the parent injector.

3. Injector

This article is reproduced from: https://www.cnblogs.com/starof/p/10506295.html


For more programming-related knowledge, please visit:

Programming 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!

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

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)

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