angular依賴注入_Angular依賴注入簡介

angular依賴注入

by Neeraj Dana

由Neeraj Dana

In this article, we will see how the dependency injection of Angular works internally. Suppose we have a component named appcomponent which has a basic and simple structure as follows:

在本文中,我們將看到Angular的依賴項注入在內部如何工作。 假設我們有一個名為appcomponent的組件,它具有如下基本且簡單的結構:

import { Component, OnInit } from "@angular/core";@Component({  selector: "my-root",  templateUrl: "app.component.html",  styleUrls: ["app.component.css"]})export class AppComponent implements OnInit {  ngOnInit(): void {      }}

And we have a service class named GreetingService with a function in it sayHello which has a name as a parameter and returns the name with “Hello” in front of it.

我們有一個名為GreetingService的服務類,其中帶有一個函數sayHello ,該函數具有一個名稱作為參數,并在其前面返回名稱為“ Hello”的名稱。

export class GreetingService{  sayHello(name){    return `Hello ${name}` ;  }}

There are two ways to use the service class in the component: first, we can manually create an instance of the service in the component (this is the wrong way and is never recommended).

在組件中使用服務類的方式有兩種:首先,我們可以在組件中手動創建服務的實例(這是錯誤的方式,從不推薦)。

And the other way is to let Angular create the instance of our service and pass that instance to our component internally. This is the common and recommended way to do it.

另一種方法是讓Angular創建服務實例并將該實例內部傳遞給我們的組件。 這是常用的推薦方法。

將我們的服務注入Angular依賴注入系統 (Injecting our service in the Angular dependency injection system)

Import {Component} from '@angular/core';Import {GreetingService} from '. /greetingService';
@Component({  selector: 'my-app',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ]})export class AppComponent  {
constructor(private greetingService : GreetingService){   console.log(this.greetingService.sayHello());  }}

Now if you run this project, you will get the error “No provider for GreetingService!”

現在,如果您運行此項目,您將收到錯誤“ No GreetingService沒有提供者!”。

So, basically Angular is complaining that it did not find any provider for creating an instance of the greeting service or it does not know how to create an instance. In order to let the framework know how the instance should be created, we have to pass a provider object to the providers property in the component decorator shown below:

因此,基本上Angular抱怨它沒有找到任何創建問候服務實例的提供程序,或者它不知道如何創建實例。 為了讓框架知道如何創建實例,我們必須將提供程序對象傳遞給組件裝飾器中的providers屬性,如下所示:

import { Component } from '@angular/core';import {GreetingService} from './greetingService';
@Component({  selector: 'my-app',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ],  providers:[{      }]})export class AppComponent  {
constructor(private greetingService : GreetingService){   console.log(this.greetingService.sayHello());  }  }

In this provider object, we have many properties so let us understand them one by one.

在此提供程序對象中,我們有許多屬性,因此讓我們一一理解它們。

定制工廠 (Custom Factory)

use factory: this will tell the framework which factory will be used while creating the object of the service. In our case, we don’t have any factory so let’s create one.

使用工廠:這將告訴框架在創建服務對象時將使用哪個工廠。 在我們的案例中,我們沒有任何工廠,因此讓我們創建一個工廠。

The factory will be a function which will be responsible for creating and returning the object of the service.

工廠將是一個負責創建和返回服務對象的功能。

export function greetingFactory(){   return  new GreetingService()};
Or more short way
export const greetingFactory= () =>  new GreetingService ();

自定義注入令牌 (Custom Injection Token)

The next thing is to create a property whose value will be an Injection Token instance. Using this property, the framework will uniquely identify our service and will inject the right instance of the service.

接下來的事情是創建一個屬性,其值將是“注入令牌”實例。 使用此屬性,框架將唯一地標識我們的服務,并將注入正確的服務實例。

var greetingTokken = new InjectionToken<GreetingService>("GREET_TOKEN");

So in the above snippet, we are creating an instance of the InjectionToken class and it is generic. In our case, the GreetingService instance will be injected when someone asks for the injection with name greetingToken.

因此,在上面的代碼段中,我們正在創建InjectionToken類的實例,并且它是通用的。 在我們的示例中,當有人要求使用名稱greetingToken進行注入時,將注入GreetingService實例。

So far now our code will look like this:

到目前為止,我們的代碼將如下所示:

import { Component ,InjectionToken} from '@angular/core';import {GreetingService} from './greetingService';
export const greetingTokken = new InjectionToken<GreetingService>("GREET_TOKEN");export const greetingFactory=()=>  new GreetingService();@Component({  selector: 'my-app',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ],  providers:[{    provide  : greetingTokken,    useFactory : greetingFactory,     }]})export class AppComponent  {
constructor(private greetingService : GreetingService){   console.log(this.greetingService.sayHello());  }  name = 'Angular';}

But then also we will have the same error:

但是然后我們也會有同樣的錯誤:

This is because in the constructor, where we are asking for the instance of our service, we have to tell it the unique string of our injection token that is greetingToken.

這是因為在構造函數中,我們在其中請求服務實例時,必須告訴它注入令牌的唯一字符串,即greetingToken

So let’s update our code:

因此,讓我們更新代碼:

export class AppComponent  {
constructor(@Inject(greetingTokken) private greetingService : GreetingService){   console.log(this.greetingService.sayHello('Neeraj'));  }  name = 'Angular';}

and now we will have the result that allows us to successfully pass a service from Angular dependency injection.

現在,我們將獲得的結果使我們能夠成功地通過Angular依賴項注入傳遞服務。

Now let us assume you have some nested dependencies like this:

現在讓我們假設您有一些嵌套的依賴項,如下所示:

import{DomSanitizer} from '@angular/platform-browser';
export class GreetingService{  constructor (private domSanitizer:DomSanitizer){      }  sayHello(name){    return `Hello ${name}`  }}

So, in this case, we have to pass one more property to the provider’s object (that is deps) which is the array of all the dependencies:

因此,在這種情況下,我們必須再傳遞一個屬性到提供者的對象(即deps),該對象是所有依賴項的數組:

@Component({  selector: 'my-app',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ],  providers:[{    provide  : greetingTokken,    useFactory : greetingFactory,    deps:[DomSanitizer]     }]})export class AppComponent  {
constructor(@Inject(greetingTokken) private greetingService : GreetingService  ){   console.log(this.greetingService.sayHello('Neeraj'));  }  name = 'Angular';}

Up until now, whatever we have done has only been for learning purposes. It is not recommended to create manual providers until there is a need.

到目前為止,我們所做的一切僅是出于學習目的。 不建議在需要之前創建手動提供程序。

So this is all the hard work done by Angular behind the scenes for us. We don’t have to do all this for registering our service. We can actually reduce the code, and instead of passing the factory and token manually, we can ask the framework to do this for us in that case.

因此,這就是Angular在后臺為我們完成的所有艱苦工作。 我們不必為注冊我們的服務而做所有這一切。 實際上,我們可以減少代碼,而不是手動傳遞工廠和令牌,在這種情況下,我們可以要求框架為我們這樣做。

The provide property, which is the injection token, will be the name of the service and Angular will internally create an injection token and factory for us.

提供屬性(即注入令牌)將是服務的名稱,Angular將在內部為我們創建注入令牌和工廠。

We have to pass one more property (use-class) which tells the framework which class we need to use:

我們必須再傳遞一個屬性(使用類),該屬性告訴框架我們需要使用哪個類:

import { Component ,InjectionToken,Inject} from '@angular/core';
import {GreetingService} from './greetingService';
@Component({  selector: 'my-app',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ],  providers:[{    provide  : GreetingService,    useClass :GreetingService     }]})export class AppComponent  {
constructor( private greetingService : GreetingService  ){   console.log(this.greetingService.sayHello('Neeraj'));  }  name = 'Angular';}

So now our code looks much cleaner and we can further reduce it by just passing the name of the service. Then Angular under the hood will create the provide object, the factory, and the injection token for us and make the instance available to us when needed.

因此,現在我們的代碼看起來更簡潔了,我們可以通過傳遞服務名稱來進一步減少代碼。 然后,Angular在幕后將為我們創建提供對象,工廠和注入令牌,并在需要時使實例可用。

import { Component } from '@angular/core';
import {GreetingService} from './greetingService';
@Component({  selector: 'my-app',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ],  providers:[GreetingService]})export class AppComponent  {
constructor( private greetingService : GreetingService  ){   console.log(this.greetingService.sayHello('Neeraj'));  }  name = 'Angular';}

So in the end, our code looks very familiar. Now in the future, whenever you create a service, you know exactly what steps are involved to get that instance available.

因此,最后,我們的代碼看起來非常熟悉。 將來,無論何時創建服務,您都確切知道要使該實例可用需要執行哪些步驟。

If you like this article follow me to get more of this kind of stuff.

如果您喜歡本文,請跟隨我獲得更多此類內容。

Visit Smartcodehub

前往Smartcodehub

翻譯自: https://www.freecodecamp.org/news/angular-dependency-injection-in-detail-8b6822d6457c/

angular依賴注入

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/392429.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392429.shtml
英文地址,請注明出處:http://en.pswp.cn/news/392429.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

leetcode 85. 最大矩形(dp)

給定一個僅包含 0 和 1 、大小為 rows x cols 的二維二進制矩陣&#xff0c;找出只包含 1 的最大矩形&#xff0c;并返回其面積。 示例 1&#xff1a; 輸入&#xff1a;matrix [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“…

如何查看系統版本

1. winR,輸入cmd&#xff0c;確定&#xff0c;打開命令窗口&#xff0c;輸入msinfo32&#xff0c;注意要在英文狀態下輸入&#xff0c;回車。然后在彈出的窗口中就可以看到系統的具體版本號了。 2.winR,輸入cmd&#xff0c;確定&#xff0c;打開命令窗口&#xff0c;輸入ver&am…

java activemq jmx_通過JMX 獲取Activemq 隊列信息

首先在 activemq.xml 中新增以下屬性在broker 節點新增屬性 useJmx"true"在managementContext 節點配置斷開與訪問服務iP配置成功后啟動下面來看測試代碼/*** Title: ActivemqTest.java* Package activemq* Description: TODO(用一句話描述該文件做什么)* author LYL…

風能matlab仿真_發現潛力:使用計算機視覺對可再生風能發電場的主要區域進行分類(第1部分)

風能matlab仿真Github Repo: https://github.com/codeamt/WindFarmSpotterGithub回購&#xff1a; https : //github.com/codeamt/WindFarmSpotter This is a series:這是一個系列&#xff1a; Part 1: A Brief Introduction on Leveraging Edge Devices and Embedded AI to …

【Leetcode_easy】821. Shortest Distance to a Character

problem 821. Shortest Distance to a Character 參考 1. Leetcode_easy_821. Shortest Distance to a Character; 完轉載于:https://www.cnblogs.com/happyamyhope/p/11214805.html

tdd測試驅動開發課程介紹_測試驅動開發的實用介紹

tdd測試驅動開發課程介紹by Luca Piccinelli通過盧卡皮奇內利 測試驅動開發很難&#xff01; 這是不為人知的事實。 (Test Driven Development is hard! This is the untold truth about it.) These days you read a ton of articles about all the advantages of doing Test …

軟件安裝(JDK+MySQL+TOMCAT)

一&#xff0c;JDK安裝 1&#xff0c;查看當前Linux系統是否已經安裝了JDK 輸入 rpm -qa | grep java 如果有&#xff1a; 卸載兩個openJDK&#xff0c;輸入rpm -e --nodeps 要卸載的軟件 2&#xff0c;上傳JDK到Linux 3&#xff0c;安裝jdk運行需要的插件yum install gl…

leetcode 205. 同構字符串(hash)

給定兩個字符串 s 和 t&#xff0c;判斷它們是否是同構的。 如果 s 中的字符可以被替換得到 t &#xff0c;那么這兩個字符串是同構的。 所有出現的字符都必須用另一個字符替換&#xff0c;同時保留字符的順序。兩個字符不能映射到同一個字符上&#xff0c;但字符可以映射自己…

Java core 包_feilong-core 讓Java開發更簡便的工具包

## 背景在JAVA開發過程中,經常看到小伙伴直接從網上copy一長段代碼來使用,又或者寫的代碼很長很長很長...**痛點在于:*** 難以閱讀* 難以維護* sonar掃描結果債務長* codereview 被小伙伴鄙視* ....feilong-core focus on J2SE,是[feilong platform](https://github.com/venusd…

TensorFlow 2.X中的動手NLP深度學習模型準備

簡介&#xff1a;為什么我寫這篇文章 (Intro: why I wrote this post) Many state-of-the-art results in NLP problems are achieved by using DL (deep learning), and probably you want to use deep learning style to solve NLP problems as well. While there are a lot …

靜態代碼塊

靜態代碼塊 靜態代碼塊&#xff1a;定義在成員位置&#xff0c;使用static修飾的代碼塊{ }。位置&#xff1a;類中方法外。執行&#xff1a;隨著類的加載而執行且執行一次&#xff0c;優先于main方法和構造方法的執行。格式&#xff1a;作用&#xff1a; 給類變量進行初始化賦值…

異步api_如何設計無服務器異步API

異步apiby Garrett Vargas通過Garrett Vargas 如何設計無服務器異步API (How To Design a Serverless Async API) I recently ran a workshop to teach developers how to create an Alexa skill. The workshop material centered around a project to return car rental sear…

C# 序列化與反序列化json

與合作伙伴討論問題&#xff0c;說到的c與c#數據的轉換調用&#xff0c;正好就說到了序列化與反序列化&#xff0c;同樣也可用于不同語言間的調用&#xff0c;做了基礎示例&#xff0c;作以下整理&#xff1a; 1 using System.Data;2 using System.Drawing;3 using System.Linq…

學java 的要點_零基礎學Java,掌握Java的基礎要點

對于程序員群體來說&#xff0c;了解一定的技巧會對學習專業技能更有幫助&#xff0c;也更有助于在自己的職業發展中處于有利地位&#xff0c;無限互聯Java培訓專家今天就為大家總結Java程序員入門時需要掌握的基礎要點&#xff1a;掌握靜態方法和屬性靜態方法和屬性用于描述某…

實驗人員考評指標_了解實驗指標

實驗人員考評指標In the first part of my series on experimental design Thinking About Experimental Design, we covered the foundations of an experiment: the goals, the conditions, and the metrics. In this post, we will move away from the initial experimental…

leetcode 188. 買賣股票的最佳時機 IV(dp)

給定一個整數數組 prices &#xff0c;它的第 i 個元素 prices[i] 是一支給定的股票在第 i 天的價格。 設計一個算法來計算你所能獲取的最大利潤。你最多可以完成 k 筆交易。 注意&#xff1a;你不能同時參與多筆交易&#xff08;你必須在再次購買前出售掉之前的股票&#xf…

kotlin編寫后臺_在Kotlin編寫圖書館的提示

kotlin編寫后臺by Adam Arold亞當阿羅德(Adam Arold) 在Kotlin編寫圖書館的提示 (Tips for Writing a Library in Kotlin) Writing a library in Kotlin seems easy but it can get tricky if you want to support multiple platforms. In this article we’ll explore ways f…

1.Swift教程翻譯系列——關于Swift

英文版PDF下載地址http://download.csdn.net/detail/tsingheng/7480427 我本來是做JAVA的。可是有一顆折騰的心&#xff0c;蘋果公布Swift以后就下載了蘋果的開發文檔。啃了幾天。朦朦朧朧的看了個幾乎相同&#xff0c;想靜下心看能不能整個翻譯出來。我英語一般般&#xff0c;…

核心技術java基礎_JAVA核心技術I---JAVA基礎知識(集合set)

一&#xff1a;集合了解(一)確定性&#xff0c;互異性&#xff0c;無序性確定性&#xff1a;對任意對象都能判定其是否屬于某一個集合互異性&#xff1a;集合內每個元素都是無差異的&#xff0c;注意是內容差異無序性&#xff1a;集合內的順序無關(二)集合接口HashSet&#xff…

nba數據庫統計_NBA板塊的價值-從統計學上講

nba數據庫統計The idea is not to block every shot. The idea is to make your opponent believe that you might block every shot. — Bill Russel這個想法不是要阻止每一個鏡頭。 這個想法是讓你的對手相信你可能會阻擋每一個投籃。 —比爾羅素 The block in basketball ha…