詳解Angular依賴注入
概述
依賴注入:設(shè)計(jì)模式
依賴:程序里需要的某種類(lèi)型的對(duì)象。
依賴注入框架:工程化的框架

注入器Injector:用它的API創(chuàng)建依賴的實(shí)例
Provider:怎樣創(chuàng)建?(構(gòu)造函數(shù),工程函數(shù))
Object:組件,模塊需要的依賴
依賴性注入進(jìn)階=>Angular中依賴注入框架提供父子層次注入型依賴
一、依賴注入
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("北京", "背景", "朝陽(yáng)區(qū)", "xx街道");
}
}
問(wèn)題:Person需要清楚的知道Address和Id的實(shí)現(xiàn)細(xì)節(jié)。
ID和Address重構(gòu)后,Person需要知道怎么重構(gòu)。
項(xiàng)目規(guī)模擴(kuò)大后,集成容易出問(wèn)題。
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(){
//把構(gòu)造依賴對(duì)象,推到上一級(jí),推調(diào)用的地方
const id = Id.getInstance("idcard");
const address = new Address("北京", "背景", "朝陽(yáng)區(qū)", "xx街道");
const person = new Person(id , address);
}
Person已經(jīng)不知道Id和Address的細(xì)節(jié)了。
這是最簡(jiǎn)單的依賴注入。
問(wèn)題是在main里還是需要知道細(xì)節(jié)。
思路:一級(jí)一級(jí)往上推,一直推到入口函數(shù),入口函數(shù)來(lái)處理所有對(duì)象的構(gòu)造。構(gòu)造出來(lái)后提供給所有依賴的子模塊的子類(lèi)。
問(wèn)題:入口函數(shù)很難維護(hù)。所以需要一個(gè)依賴注入框架幫助完成。
二、Angular的依賴注入框架
從v5開(kāi)始,因?yàn)樗俣嚷?,引入大量代碼已棄用,改為Injector.create。
ReflectiveInjector :用于實(shí)例化對(duì)象和解析依賴關(guān)系。import { Component ,ReflectiveInjector } from "@angular/core";resolveAndCreate接收一個(gè)provider數(shù)組,provider告訴injector應(yīng)該怎樣去構(gòu)造這個(gè)對(duì)象。
constructor() {
//接收一個(gè)provider數(shù)組
const injector = ReflectiveInjector.resolveAndCreate([
{
provide: Person, useClass:Person
},
{
provide: Address, useFactory: ()=>{
if(environment.production){
return new Address("北京", "背景", "朝陽(yáng)區(qū)", "xx街道xx號(hào)");
}else{
return new Address("西藏", "拉薩", "xx區(qū)", "xx街道xx號(hào)");
}
}
},
{
provide: Id, useFactory:()=>{
return Id.getInstance('idcard');
}
}
]);
}
Injector:
injector相當(dāng)于main函數(shù),可以拿到所有依賴池子里的東西。
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) {
//接收一個(gè)provider數(shù)組
const injector = ReflectiveInjector.resolveAndCreate([
{
provide: Person, useClass:Person
},
{
provide: Address, useFactory: ()=>{
if(environment.production){
return new Address("北京", "背景", "朝陽(yáng)區(qū)", "xx街道xx號(hào)");
}else{
return new Address("西藏", "拉薩", "xx區(qū)", "xx街道xx號(hào)");
}
}
},
{
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;
}
}
可以看到控制臺(tái)打印出person信息。

簡(jiǎn)寫(xiě):
// {
// provide: Person, useClass:Person
// },
Person, //簡(jiǎn)寫(xiě)為Person
在Angular框架中,框架做了很多事,在provider數(shù)組中注冊(cè)的東西會(huì)自動(dòng)注冊(cè)到池子中。
@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); //控制臺(tái)打印出http://localhost:3000
}
Angular默認(rèn)都是單例,如果想要每次注入都是一個(gè)新的實(shí)例。有兩種方法。
一,return的時(shí)候return一個(gè)方法而不是對(duì)象。
{
provide: Address, useFactory: ()=>{
return ()=>{
if(environment.production){
return new Address("北京", "背景", "朝陽(yáng)區(qū)", "xx街道xx號(hào)");
}else{
return new Address("西藏", "拉薩", "xx區(qū)", "xx街道xx號(hào)");
}
}
}
},
二、利用父子Injector。
constructor(private oc: OverlayContainer) {
//接收一個(gè)provider數(shù)組
const injector = ReflectiveInjector.resolveAndCreate([
Person,
{
provide: Address, useFactory: ()=>{
if(environment.production){
return new Address("北京", "背景", "朝陽(yáng)區(qū)", "xx街道xx號(hào)");
}else{
return new Address("西藏", "拉薩", "xx區(qū)", "xx街道xx號(hào)");
}
}
},
{
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
}
子注入器當(dāng)中沒(méi)有找到依賴的時(shí)候會(huì)去父注入器中找
以上就是詳解Angular依賴注入的詳細(xì)內(nèi)容,更多關(guān)于Angular的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- angular 服務(wù)的單例模式(依賴注入模式下)詳解
- 深入理解Angular中的依賴注入
- Angular 4依賴注入學(xué)習(xí)教程之InjectToken的使用(八)
- Angular 4依賴注入學(xué)習(xí)教程之ValueProvider的使用(七)
- AngularJS學(xué)習(xí)第二篇 AngularJS依賴注入
- AngularJS的依賴注入實(shí)例分析(使用module和injector)
- 自學(xué)實(shí)現(xiàn)angularjs依賴注入
- Angular.JS學(xué)習(xí)之依賴注入$injector詳析
- AngularJS $injector 依賴注入詳解
相關(guān)文章
Angular應(yīng)用程序的Hydration基本概念詳解
這篇文章主要為大家介紹了Angular應(yīng)用程序的Hydration基本概念詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09
AngularJS 自定義過(guò)濾器詳解及實(shí)例代碼
這篇文章主要介紹了AngularJS 自定義過(guò)濾器,這里整理了相關(guān)資料及示例代碼,有興趣的小伙伴可以參考下2016-09-09
每個(gè)Angular版本在其生命周期中都經(jīng)歷了各個(gè)階段。組件在Angular中起著關(guān)鍵作用; 在這里,本文將討論Angular中的組件生命周期以及它們?nèi)绾斡绊懣蚣芩邪姹镜纳芷凇?/div> 2021-05-05
AngularJS bootstrap啟動(dòng)詳解及實(shí)例代碼
這篇文章主要介紹了AngularJS bootstrap啟動(dòng)的知識(shí),這里整理了相關(guān)資料及簡(jiǎn)單實(shí)例代碼,,需要的朋友可以參考下2016-09-09
在 Angular 中使用Chart.js 和 ng2-charts的示例代碼
本篇文章主要介紹了在 Angular 中使用Chart.js 和 ng2-charts的示例代碼,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08
Angular實(shí)現(xiàn)搜索框及價(jià)格上下限功能
這篇文章主要為大家詳細(xì)介紹了Angular實(shí)現(xiàn)搜索框及價(jià)格上下限功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
Angularjs中$http以post請(qǐng)求通過(guò)消息體傳遞參數(shù)的實(shí)現(xiàn)方法
這篇文章主要介紹了Angularjs中$http以post請(qǐng)求通過(guò)消息體傳遞參數(shù)的方法,結(jié)合實(shí)例形式分析了$http使用post請(qǐng)求傳遞參數(shù)的相關(guān)設(shè)置與使用技巧,需要的朋友可以參考下2016-08-08
Angular5給組件本身的標(biāo)簽添加樣式class的方法
本篇文章主要介紹了Angular 5 給組件本身的標(biāo)簽添加樣式class的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04最新評(píng)論

