Angular의 의존성 주입에 대해 알아봅시다.

青灯夜游
풀어 주다: 2021-02-22 17:55:56
앞으로
1463명이 탐색했습니다.

이 글에서는 Angular의 종속성 주입을 소개합니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

Angular의 의존성 주입에 대해 알아봅시다.

관련 추천: "angular tutorial"

종속성 주입: 디자인 패턴

종속성: 프로그램에 필요한 특정 유형의 객체.

종속성 주입 프레임워크: 엔지니어링 프레임워크

인젝터: API를 사용하여 종속 인스턴스를 생성합니다.

공급자: 어떻게 생성하나요? (생성자, 엔지니어링 함수)

객체: 컴포넌트 및 모듈에 필요한 종속성

고급 종속성 주입 => Angular의 종속성 주입 프레임워크는 부모-자식 계층적 주입유형 종속성

을 제공합니다. 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와 주소의 세부 사항을 모릅니다.

이것은 가장 간단한 의존성 주입입니다.

문제가 기본이거나 자세한 내용을 알고 싶습니다.

아이디어: 모든 객체의 구성을 처리하는 입력 기능까지 한 번에 한 레벨씩 밀어 올리세요. 모든 종속 하위 모듈에 생성되어 제공되는 하위 클래스입니다.

문제: 입력 기능을 유지하기가 어렵습니다. 따라서 이를 완료하는 데 도움이 되는 종속성 주입 프레임워크가 필요합니다.

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는 매번 새 인스턴스를 주입하려는 경우 기본적으로 싱글톤입니다. 두 가지 방법이 있습니다.

먼저, 반환할 때 객체 대신 메서드를 반환하세요.

{
        provide: Address, useFactory: ()=>{
          return ()=>{
            if(environment.production){
              return new Address("北京", "背景", "朝阳区", "xx街道xx号");
            }else{
              return new Address("西藏", "拉萨", "xx区", "xx街道xx号");
            }
          }
        }
      },
로그인 후 복사

둘째, 부자주사기를 사용해보세요.

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. Injector

이 기사는 https://www.cnblogs.com/starof/p/10506295.html

더 많은 프로그래밍 관련 지식을 보려면 다음을 방문하세요. 프로그래밍 교육 ! !

위 내용은 Angular의 의존성 주입에 대해 알아봅시다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:cnblogs.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!