詳解Angular依賴註入

概述

依賴註入:設計模式

依賴:程序裡需要的某種類型的對象。

依賴註入框架:工程化的框架

註入器Injector:用它的API創建依賴的實例

Provider:怎樣創建?(構造函數,工程函數)

Object:組件,模塊需要的依賴

依賴性註入進階=>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("北京", "背景", "朝陽區", "xx街道");
  }
}

問題:Person需要清楚的知道Address和Id的實現細節。

ID和Address重構後,Person需要知道怎麼重構。

項目規模擴大後,集成容易出問題。

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已經不知道Id和Address的細節瞭。

這是最簡單的依賴註入。

問題是在main裡還是需要知道細節。

思路:一級一級往上推,一直推到入口函數,入口函數來處理所有對象的構造。構造出來後提供給所有依賴的子模塊的子類。

問題:入口函數很難維護。所以需要一個依賴註入框架幫助完成。

二、Angular的依賴註入框架

從v5開始,因為速度慢,引入大量代碼已棄用,改為Injector.create。

ReflectiveInjector :用於實例化對象和解析依賴關系。import { Component ,ReflectiveInjector } from “@angular/core”;resolveAndCreate接收一個provider數組,provider告訴injector應該怎樣去構造這個對象。

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相當於main函數,可以拿到所有依賴池子裡的東西。

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;
  }
}

可以看到控制臺打印出person信息。

簡寫:

 // {
      //   provide: Person, useClass:Person
      // },
      Person, //簡寫為Person

在Angular框架中,框架做瞭很多事,在provider數組中註冊的東西會自動註冊到池子中。

@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
  }

Angular默認都是單例,如果想要每次註入都是一個新的實例。有兩種方法。

一,return的時候return一個方法而不是對象。

{
    provide: Address, useFactory: ()=>{
        return ()=>{
            if(environment.production){
                return new Address("北京", "背景", "朝陽區", "xx街道xx號");
            }else{
                return new Address("西藏", "拉薩", "xx區", "xx街道xx號");
            }
        }
    }
},

二、利用父子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
  }

子註入器當中沒有找到依賴的時候會去父註入器中找

以上就是詳解Angular依賴註入的詳細內容,更多關於Angular的資料請關註WalkonNet其它相關文章!

推薦閱讀: