Table of Contents
1. Component communication
2. Dependency Injection
Home Web Front-end JS Tutorial Take you to understand component communication and dependency injection in Angular

Take you to understand component communication and dependency injection in Angular

Sep 22, 2021 am 10:28 AM
angular dependency injection Component communication

AngularHow to communicate between components? What is dependency injection? The following article will give you a brief understanding of the component communication method and introduce dependency injection. I hope it will be helpful to you!

Take you to understand component communication and dependency injection in Angular

1. Component communication

##1.1 Passing data to the inside of the component

<app-favorite [isFavorite]="true"></app-favorite>
Copy after login
// favorite.component.ts
import { Input } from &#39;@angular/core&#39;;

export class FavoriteComponent {
    @Input() isFavorite: boolean = false;
}
Copy after login

Note: Add

[] outside the attribute to indicate binding the dynamic value. After receiving it in the component, it will be a Boolean type. Do not add [] to indicate Bind a normal value, which is a string type after being received in the component. [Related tutorial recommendations: "angular tutorial"]

1.2 Components transmit data to the outside

Requirements : Pass data to the parent component by clicking the button in the child component

<!-- 子组件模板 -->
<button (click)="onClick()">click</button>
Copy after login
// 子组件类
import { EventEmitter, Output } from "@angular/core"

export class FavoriteComponent {
  @Output() change = new EventEmitter()
  onClick() {
    this.change.emit({ name: "张三" })
  }
}
Copy after login
<!-- 父组件模板 -->
<app-favorite (change)="onChange($event)"></app-favorite>
Copy after login
// 父组件类
export class AppComponent {
  onChange(event: { name: string }) {
    console.log(event)
  }
}
Copy after login


2. Dependency Injection

2.1 Overview

Dependency injection (

Dependency Injection), referred to as DI, is a design principle in object-oriented programming that is used to reduce the coupling between codes Degree

class MailService {
  constructor(APIKEY) {}
}

class EmailSender {
  mailService: MailService
  constructor() {
    this.mailService = new MailService("APIKEY1234567890")
  }

  sendMail(mail) {
    this.mailService.sendMail(mail)
  }
}

const emailSender = new EmailSender()
emailSender.sendMail(mail)
Copy after login

EmailSender class must use the MailService class when running, EmailSender class depends on the MailService class, The MailService class is a dependency of the EmailSender class.

The coupling degree of the above writing method is too high, and the code is not robust. If the

MailService class changes the parameter delivery method, the writing method in the EmailSender class will also change

class EmailSender {
  mailService: MailService
  constructor(mailService: MailService) {
    this.mailService = mailService;
  }
}
const mailService = new MailService("APIKEY1234567890")
const emailSender = new EmailSender(mailService)
Copy after login

when instantiating the

EmailSender class When injecting its dependencies into the interior of the class in the form of constructor constructor parameters, this way of writing is dependency injection.

Through dependency injection, the coupling between codes is reduced and the maintainability of the code is increased.

MailService Changes to the code in the class will no longer affect the EmailSender class

2.2 DI Framework

Angular has its own DI framework, which hides the process of implementing dependency injection. For developers, only Complex dependency injection functionality can be used with very simple code.

There are four core concepts in

Angular's DI framework:

  • Dependency: The instance object on which the component depends, service instance object

  • Token: Get the identifier of the service instance object

  • Injector: Injector, responsible for creating and maintaining instance objects of service classes and injecting service instance objects into components.

  • Provider: Configure the object of the injector, specify the service class to create the service instance object and obtain the identifier of the instance object.

2.2.1 InjectorsInjectors

The injector is responsible for creating service class instance objects and converting service class instances to Inject the object into the required component

  • Create the injector

    import { ReflectiveInjector } from "@angular/core"
    // 服务类
    class MailService {}
    // 创建注入器并传入服务类
    const injector = ReflectiveInjector.resolveAndCreate([MailService])
    Copy after login

  • Get the service class instance object in the injector

    const mailService = injector.get(MailService)
    Copy after login

  • The service instance object is in singleton mode, and the injector will cache it after creating the service instance.

    const mailService1 = injector.get(MailService)
    const mailService2 = injector.get(MailService)
    
    console.log(mailService1 === mailService2) // true
    Copy after login

  • Different injectors return different service instance objects

    const injector = ReflectiveInjector.resolveAndCreate([MailService])
    const childInjector = injector.resolveAndCreateChild([MailService])
    
    const mailService1 = injector.get(MailService)
    const mailService2 = childInjector.get(MailService)
    
    console.log(mailService1 === mailService2) // false
    Copy after login

  • The search for service instances is similar to the function scope chain. If the current level can be found, use the current level. If the current level cannot be found, go to the parent to find it

    const injector = ReflectiveInjector.resolveAndCreate([MailService])
    const childInjector = injector.resolveAndCreateChild([])
    
    const mailService1 = injector.get(MailService)
    const mailService2 = childInjector.get(MailService)
    
    console.log(mailService1 === mailService2) // true
    Copy after login

2.2.2 ProviderProvider

  • Configure the object of the injector, specifying the service class and creation instance object The identifier of the access service instance object

    const injector = ReflectiveInjector.resolveAndCreate([
      { provide: MailService, useClass: MailService }
    ])
    Copy after login

  • The identifier of the access dependent object can also be a string type

    const injector = ReflectiveInjector.resolveAndCreate([
      { provide: "mail", useClass: MailService }
    ])
    const mailService = injector.get("mail")
    Copy after login

  • useValue

    const injector = ReflectiveInjector.resolveAndCreate([
      {
        provide: "Config",
        useValue: Object.freeze({
          APIKEY: "API1234567890",
          APISCRET: "500-400-300"
        })
      }
    ])
    const Config = injector.get("Config")
    Copy after login

    Establishes a loose coupling relationship between the instance object and the external reference. The external object obtains the instance object through the identifier. As long as the identifier remains unchanged, no matter how the internal code changes, it will not affect the outside world

    For more programming-related knowledge, please visit:

    Programming Video! !

    The above is the detailed content of Take you to understand component communication and 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