Angular での依存関係の注入について学びましょう

青灯夜游
リリース: 2021-02-22 17:55:56
転載
1464 人が閲覧しました

この記事では、Angular での依存関係注入について紹介します。一定の参考値があるので、困っている友達が参考になれば幸いです。

Angular での依存関係の注入について学びましょう

関連する推奨事項: "angular チュートリアル "

依存関係の挿入: 設計パターン

依存関係:プログラム 何らかのタイプの オブジェクト

Dependency Injection Framework: エンジニアリング フレームワーク

Injector: API を使用して依存関係のインスタンスを作成します

Provider: どのように作成しますか? (コンストラクター、エンジニアリング関数)

オブジェクト: コンポーネントとモジュールに必要な依存関係

高度な依存関係注入=>Angular の依存関係注入フレームワークは、親子 階層型注入を提供します。 Type dependency

1. 依存関係の注入

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街道");
  }
}
ログイン後にコピー

問題: アドレスと ID の実装の詳細を明確に知っている必要があります。

ID とアドレスが再構築された後、ユーザーはそれらを再構築する方法を知る必要があります。

プロジェクトの規模が拡大すると、統合の問題が発生しやすくなります。

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);
}
ログイン後にコピー

本人はIDと住所の詳細を知りません。

これは最も単純な依存関係の注入です。

問題は主なものですか、それとも詳細を知る必要があります。

アイデア: すべてのオブジェクトの構築を処理するエントリ関数まで、一度に 1 レベルずつ押し上げます。構築され、すべての依存サブモジュールに提供されるサブクラス。

問題: エントリ関数の保守は困難です。したがって、これを完了するには依存関係注入フレームワークが必要です。

2. Angular の依存関係注入フレームワーク

v5 以降、速度が遅いことと、大量のコードの導入。Injector.create を変更。

ReflectiveInjector : オブジェクトをインスタンス化し、依存関係を解決するために使用されます。

import { Component ,ReflectiveInjector } from "@angular/core";
ログイン後にコピー

resolveAndCreate はプロバイダー配列を受け取り、プロバイダーはインジェクターにオブジェクトの構築方法を指示します。

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;
  }
}
ログイン後にコピー

コンソールに出力された個人情報を確認できます。

略称:

      // {
      //   provide: Person, useClass:Person
      // },
      Person, //简写为Person
ログイン後にコピー

Angular フレームワークではフレームワークが多くのことを行っており、プロバイダー配列に登録されたものは自動的にプールに登録されます。

@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 はデフォルトではシングルトンです。毎回新しいインスタンスを挿入したい場合。方法は 2 つあります。

まず、返すときにオブジェクトではなくメソッドを返します。

{
        provide: Address, useFactory: ()=>{
          return ()=>{
            if(environment.production){
              return new Address("北京", "背景", "朝阳区", "xx街道xx号");
            }else{
              return new Address("西藏", "拉萨", "xx区", "xx街道xx号");
            }
          }
        }
      },
ログイン後にコピー

2. 親子インジェクターを使用します。

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
  }
ログイン後にコピー
依存関係が子インジェクターで見つからない場合は、親インジェクターで依存関係を探します。

3. インジェクター

この記事は、https://www.cnblogs.com/starof/p/10506295.html から転載されました。


プログラミング関連の知識について詳しくは、

プログラミング教育をご覧ください。 !

以上がAngular での依存関係の注入について学びましょうの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:cnblogs.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!