>  기사  >  웹 프론트엔드  >  Angular의 메타데이터와 데코레이터에 대해 이야기해 보겠습니다.

Angular의 메타데이터와 데코레이터에 대해 이야기해 보겠습니다.

青灯夜游
青灯夜游앞으로
2022-02-28 11:10:442181검색

이 기사는 Angular에 대한 학습을 ​​계속하고 Angular의 메타데이터와 데코레이터를 이해하고 그 사용법을 간략하게 이해하는 데 도움이 되기를 바랍니다.

Angular의 메타데이터와 데코레이터에 대해 이야기해 보겠습니다.

"대규모 프런트엔드 프로젝트용"으로 설계된 프런트엔드 프레임워크로서 Angular에는 실제로 참고하고 학습할 만한 디자인이 많이 있습니다. 이 시리즈는 주로 이러한 디자인과 기능의 구현 원리를 연구하는 데 사용됩니다. 이번 글에서는 Angular 어디에서나 볼 수 있는 메타데이터를 주로 소개합니다. [추천 관련 튜토리얼: "angular Tutorial"]

Decorator는 Angular로 개발할 때 핵심 개념입니다. Angular에서 데코레이터는 클래스나 속성에 메타데이터를 첨부하여 해당 클래스나 속성의 의미와 처리 방법을 알려주는 데 사용됩니다.

데코레이터와 메타데이터

데코레이터나 메타데이터는 모두 Angular가 제안한 개념이 아닙니다. 그럼 먼저 간단히 살펴보겠습니다.

Metadata

일반적인 개념에서 메타데이터는 사용자 데이터를 설명하는 데이터입니다. 여기에는 데이터에 대한 기본 정보가 요약되어 있으며 특정 데이터 인스턴스를 보다 쉽게 ​​찾고 사용할 수 있습니다. 예를 들어 작성자, 생성 날짜, 수정 날짜 및 파일 크기는 매우 기본적인 문서 메타데이터의 예입니다.

클래스의 경우 클래스의 정의와 동작을 설명하기 위해 클래스를 장식하는 데 메타데이터를 사용하여 클래스의 예상 동작을 구성할 수 있습니다.

Decorator

Decorator는 JavaScript의 언어 기능이자 2단계의 실험적 기능입니다.

데코레이터는 클래스, 클래스 요소 또는 기타 JavaScript 구문 형식을 정의하는 동안 호출되는 함수입니다.

데코레이터에는 세 가지 주요 기능이 있습니다.

  • 데코레이션되는 값을 동일한 의미를 갖는 일치하는 값으로 대체할 수 있습니다. (예를 들어 데코레이터는 메서드를 다른 메서드로, 한 필드를 다른 필드로, 한 클래스를 다른 클래스로 바꾸는 식으로 바꿀 수 있습니다.)

  • 메타데이터를 수정 중인 값과 연결할 수 있습니다. 이 메타데이터는 외부에서 읽을 수 있으며 메타프로그래밍 및 자체 검사에 사용될 수 있습니다.

  • 수정되는 값에 대한 액세스는 메타데이터를 통해 제공될 수 있습니다. 공개 값의 경우 값 이름을 통해 이를 수행하고 비공개 값의 경우 선택적으로 공유할 수 있는 접근자 함수를 받습니다.

기본적으로 데코레이터는 외부 동작을 근본적으로 변경하지 않고도 값을 메타프로그래밍하고 기능을 추가하는 데 사용할 수 있습니다.

자세한 내용은 tc39/proposal-designators 제안서를 참조하세요.

Angular의 데코레이터 및 메타데이터

구성 요소, 명령, 서비스, 모듈 등 Angular 애플리케이션을 개발할 때 데코레이터를 사용하여 이를 정의하고 개발해야 합니다. 데코레이터는 클래스 정의 바로 앞에 나타나며 클래스에 지정된 유형이 있음을 선언하고 해당 유형에 적합한 메타데이터를 제공하는 데 사용됩니다.

예를 들어, 다음 데코레이터를 사용하여 Angular 클래스를 선언할 수 있습니다: @Component(), @Directive(), @Pipe(), @Injectable(), @NgModule(). @Component()@Directive()@Pipe()@Injectable()@NgModule()

使用装饰器和元数据来改变类的行为

@Component()为例,该装饰器的作用包括:

  • 将类标记为 Angular 组件。

  • 提供可配置的元数据,用来确定应在运行时如何处理、实例化和使用该组件。

关于@Component()该如何使用可以参考,这里不多介绍。我们来看看这个装饰器的定义:

// 提供 Angular 组件的配置元数据接口定义
// Angular 中,组件是指令的子集,始终与模板相关联
export interface Component extends Directive {
  // changeDetection 用于此组件的变更检测策略
  // 实例化组件时,Angular 将创建一个更改检测器,该更改检测器负责传播组件的绑定。
  changeDetection?: ChangeDetectionStrategy;
  // 定义对其视图 DOM 子对象可见的可注入对象的集合
  viewProviders?: Provider[];
  // 包含组件的模块的模块ID,该组件必须能够解析模板和样式的相对 URL
  moduleId?: string;
  ...
  // 模板和 CSS 样式的封装策略
  encapsulation?: ViewEncapsulation;
  // 覆盖默认的插值起始和终止定界符(`{{`和`}}`)
  interpolation?: [string, string];
}

// 组件装饰器和元数据
export const Component: ComponentDecorator = makeDecorator(
    'Component',
    // 使用默认的 CheckAlways 策略,在该策略中,更改检测是自动进行的,直到明确停用为止。
    (c: Component = {}) => ({changeDetection: ChangeDetectionStrategy.Default, ...c}),
    Directive, undefined,
    (type: Type<any>, meta: Component) => SWITCH_COMPILE_COMPONENT(type, meta));

以上便是组件装饰、组件元数据的定义,我们来看看装饰器的创建过程。

装饰器的创建过程

我们可以从源码中找到,组件和指令的装饰器都会通过makeDecorator()来产生:

export function makeDecorator<T>(
    name: string, props?: (...args: any[]) => any, parentClass?: any, // 装饰器名字和属性
    additionalProcessing?: (type: Type<T>) => void,
    typeFn?: (type: Type<T>, ...args: any[]) => void):
    {new (...args: any[]): any; (...args: any[]): any; (...args: any[]): (cls: any) => any;} {
  // noSideEffects 用于确认闭包编译器包装的函数没有副作用
  return noSideEffects(() => { 
    const metaCtor = makeMetadataCtor(props);
    // 装饰器工厂
    function DecoratorFactory(
        this: unknown|typeof DecoratorFactory, ...args: any[]): (cls: Type<T>) => any {
      if (this instanceof DecoratorFactory) {
        // 赋值元数据
        metaCtor.call(this, ...args);
        return this as typeof DecoratorFactory;
      }
      // 创建装饰器工厂
      const annotationInstance = new (DecoratorFactory as any)(...args);
      return function TypeDecorator(cls: Type<T>) {
        // 编译类
        if (typeFn) typeFn(cls, ...args);
        // 使用 Object.defineProperty 很重要,因为它会创建不可枚举的属性,从而防止该属性在子类化过程中被复制。
        const annotations = cls.hasOwnProperty(ANNOTATIONS) ?
            (cls as any)[ANNOTATIONS] :
            Object.defineProperty(cls, ANNOTATIONS, {value: []})[ANNOTATIONS];
        annotations.push(annotationInstance);
        // 特定逻辑的执行
        if (additionalProcessing) additionalProcessing(cls);

        return cls;
      };
    }
    if (parentClass) {
      // 继承父类
      DecoratorFactory.prototype = Object.create(parentClass.prototype);
    }
    DecoratorFactory.prototype.ngMetadataName = name;
    (DecoratorFactory as any).annotationCls = DecoratorFactory;
    return DecoratorFactory as any;
  });
}

在上面的例子中,我们通过makeDecorator()产生了一个用于定义组件的Component装饰器工厂。当使用@Component()创建组件时,Angular 会根据元数据来编译组件。

根据装饰器元数据编译组件

Angular 会根据该装饰器元数据,来编译 Angular 组件,然后将生成的组件定义(ɵcmp

🎜🎜데코레이터와 메타데이터를 사용하여 클래스 동작 변경🎜🎜🎜🎜 @Component()를 예로 들면 이 데코레이터의 기능은 다음과 같습니다. 🎜🎜🎜🎜클래스를 다음으로 표시 각도 구성 요소. 🎜🎜🎜🎜구성 요소가 런타임에 처리, 인스턴스화 및 사용되는 방법을 결정하는 구성 가능한 메타데이터를 제공합니다. 🎜🎜🎜🎜@Component() 사용법은 🎜, 여기에는 소개가 많지 않습니다. 이 데코레이터의 정의를 살펴보겠습니다. 🎜
export function compileComponent(type: Type<any>, metadata: Component): void {
  // 初始化 ngDevMode
  (typeof ngDevMode === &#39;undefined&#39; || ngDevMode) && initNgDevMode();
  let ngComponentDef: any = null;
  // 元数据可能具有需要解析的资源
  maybeQueueResolutionOfComponentResources(type, metadata);
  // 这里使用的功能与指令相同,因为这只是创建 ngFactoryDef 所需的元数据的子集
  addDirectiveFactoryDef(type, metadata);
  Object.defineProperty(type, NG_COMP_DEF, {
    get: () => {
      if (ngComponentDef === null) {
        const compiler = getCompilerFacade();
        // 根据元数据解析组件
        if (componentNeedsResolution(metadata)) {
          ...
          // 异常处理
        }
        ...
        // 创建编译组件需要的完整元数据
        const templateUrl = metadata.templateUrl || `ng:///${type.name}/template.html`;
        const meta: R3ComponentMetadataFacade = {
          ...directiveMetadata(type, metadata),
          typeSourceSpan: compiler.createParseSourceSpan(&#39;Component&#39;, type.name, templateUrl),
          template: metadata.template || &#39;&#39;,
          preserveWhitespaces,
          styles: metadata.styles || EMPTY_ARRAY,
          animations: metadata.animations,
          directives: [],
          changeDetection: metadata.changeDetection,
          pipes: new Map(),
          encapsulation,
          interpolation: metadata.interpolation,
          viewProviders: metadata.viewProviders || null,
        };
        // 编译过程需要计算深度,以便确认编译是否最终完成
        compilationDepth++;
        try {
          if (meta.usesInheritance) {
            addDirectiveDefToUndecoratedParents(type);
          }
          // 根据模板、环境和组件需要的元数据,来编译组件
          ngComponentDef = compiler.compileComponent(angularCoreEnv, templateUrl, meta);
        } finally {
          // 即使编译失败,也请确保减少编译深度
          compilationDepth--;
        }
        if (compilationDepth === 0) {
          // 当执行 NgModule 装饰器时,我们将模块定义加入队列,以便仅在所有声明都已解析的情况下才将队列出队,并将其自身作为模块作用域添加到其所有声明中
          // 此调用运行检查以查看队列中的任何模块是否可以出队,并将范围添加到它们的声明中
          flushModuleScopingQueueAsMuchAsPossible();
        }
        // 如果组件编译是异步的,则声明该组件的 @NgModule 批注可以执行并在组件类型上设置 ngSelectorScope 属性
        // 这允许组件在完成编译后,使用模块中的 directiveDefs 对其自身进行修补
        if (hasSelectorScope(type)) {
          const scopes = transitiveScopesFor(type.ngSelectorScope);
          patchComponentDefWithScope(ngComponentDef, scopes);
        }
      }
      return ngComponentDef;
    },
    ...
  });
}
🎜위는 컴포넌트 데코레이션과 컴포넌트 메타데이터의 정의입니다. 🎜🎜🎜🎜데코레이터 생성 과정🎜🎜🎜🎜구성 요소 및 지침에 대한 데코레이터는 makeDecorator()를 통해 생성됩니다. 🎜
export class CompileMetadataResolver {
  private _nonNormalizedDirectiveCache =
      new Map<Type, {annotation: Directive, metadata: cpl.CompileDirectiveMetadata}>();
  // 使用 Map 的方式来保存
  private _directiveCache = new Map<Type, cpl.CompileDirectiveMetadata>(); 
  private _summaryCache = new Map<Type, cpl.CompileTypeSummary|null>();
  private _pipeCache = new Map<Type, cpl.CompilePipeMetadata>();
  private _ngModuleCache = new Map<Type, cpl.CompileNgModuleMetadata>();
  private _ngModuleOfTypes = new Map<Type, Type>();
  private _shallowModuleCache = new Map<Type, cpl.CompileShallowModuleMetadata>();

  constructor(
      private _config: CompilerConfig, private _htmlParser: HtmlParser,
      private _ngModuleResolver: NgModuleResolver, private _directiveResolver: DirectiveResolver,
      private _pipeResolver: PipeResolver, private _summaryResolver: SummaryResolver<any>,
      private _schemaRegistry: ElementSchemaRegistry,
      private _directiveNormalizer: DirectiveNormalizer, private _console: Console,
      private _staticSymbolCache: StaticSymbolCache, private _reflector: CompileReflector,
      private _errorCollector?: ErrorCollector) {}
  // 清除特定某个指令的元数据
  clearCacheFor(type: Type) {
    const dirMeta = this._directiveCache.get(type);
    this._directiveCache.delete(type);
    ...
  }
  // 清除所有元数据
  clearCache(): void {
    this._directiveCache.clear();
    ...
  }
  /**
   * 加载 NgModule 中,已声明的指令和的管道
   */
  loadNgModuleDirectiveAndPipeMetadata(moduleType: any, isSync: boolean, throwIfNotFound = true):
      Promise<any> {
    const ngModule = this.getNgModuleMetadata(moduleType, throwIfNotFound);
    const loading: Promise<any>[] = [];
    if (ngModule) {
      ngModule.declaredDirectives.forEach((id) => {
        const promise = this.loadDirectiveMetadata(moduleType, id.reference, isSync);
        if (promise) {
          loading.push(promise);
        }
      });
      ngModule.declaredPipes.forEach((id) => this._loadPipeMetadata(id.reference));
    }
    return Promise.all(loading);
  }
  // 加载指令(组件)元数据
  loadDirectiveMetadata(ngModuleType: any, directiveType: any, isSync: boolean): SyncAsync<null> {
    // 若已加载,则直接返回
    if (this._directiveCache.has(directiveType)) {
      return null;
    }
    directiveType = resolveForwardRef(directiveType);
    const {annotation, metadata} = this.getNonNormalizedDirectiveMetadata(directiveType)!;
    // 创建指令(组件)元数据
    const createDirectiveMetadata = (templateMetadata: cpl.CompileTemplateMetadata|null) => {
      const normalizedDirMeta = new cpl.CompileDirectiveMetadata({
        isHost: false,
        type: metadata.type,
        isComponent: metadata.isComponent,
        selector: metadata.selector,
        exportAs: metadata.exportAs,
        changeDetection: metadata.changeDetection,
        inputs: metadata.inputs,
        outputs: metadata.outputs,
        hostListeners: metadata.hostListeners,
        hostProperties: metadata.hostProperties,
        hostAttributes: metadata.hostAttributes,
        providers: metadata.providers,
        viewProviders: metadata.viewProviders,
        queries: metadata.queries,
        guards: metadata.guards,
        viewQueries: metadata.viewQueries,
        entryComponents: metadata.entryComponents,
        componentViewType: metadata.componentViewType,
        rendererType: metadata.rendererType,
        componentFactory: metadata.componentFactory,
        template: templateMetadata
      });
      if (templateMetadata) {
        this.initComponentFactory(metadata.componentFactory!, templateMetadata.ngContentSelectors);
      }
      // 存储完整的元数据信息,以及元数据摘要信息
      this._directiveCache.set(directiveType, normalizedDirMeta);
      this._summaryCache.set(directiveType, normalizedDirMeta.toSummary());
      return null;
    };

    if (metadata.isComponent) {
      // 如果是组件,该过程可能为异步过程,则需要等待异步过程结束后的模板返回
      const template = metadata.template !;
      const templateMeta = this._directiveNormalizer.normalizeTemplate({
        ngModuleType,
        componentType: directiveType,
        moduleUrl: this._reflector.componentModuleUrl(directiveType, annotation),
        encapsulation: template.encapsulation,
        template: template.template,
        templateUrl: template.templateUrl,
        styles: template.styles,
        styleUrls: template.styleUrls,
        animations: template.animations,
        interpolation: template.interpolation,
        preserveWhitespaces: template.preserveWhitespaces
      });
      if (isPromise(templateMeta) && isSync) {
        this._reportError(componentStillLoadingError(directiveType), directiveType);
        return null;
      }
      // 并将元数据进行存储
      return SyncAsync.then(templateMeta, createDirectiveMetadata);
    } else {
      // 指令,直接存储元数据
      createDirectiveMetadata(null);
      return null;
    }
  }
  // 获取给定指令(组件)的元数据信息
  getDirectiveMetadata(directiveType: any): cpl.CompileDirectiveMetadata {
    const dirMeta = this._directiveCache.get(directiveType)!;
    ...
    return dirMeta;
  }
  // 获取给定指令(组件)的元数据摘要信息
  getDirectiveSummary(dirType: any): cpl.CompileDirectiveSummary {
    const dirSummary =
        <cpl.CompileDirectiveSummary>this._loadSummary(dirType, cpl.CompileSummaryKind.Directive);
    ...
    return dirSummary;
  }
}
🎜위 예에서는 makeDecorator()를 사용하여 구성 요소 정의를 위한 Component 데코레이터 팩토리를 생성합니다. @Component()를 사용하여 구성 요소를 생성하면 Angular는 메타데이터를 기반으로 구성 요소를 컴파일합니다. 🎜🎜🎜🎜데코레이터 메타데이터를 기반으로 구성 요소 컴파일🎜🎜🎜🎜Angular는 데코레이터 메타데이터를 기반으로 Angular 구성 요소를 컴파일한 다음 생성된 구성 요소 정의(ɵcmp)를 구성 요소 유형에 패치합니다.🎜
export function compileComponent(type: Type<any>, metadata: Component): void {
  // 初始化 ngDevMode
  (typeof ngDevMode === &#39;undefined&#39; || ngDevMode) && initNgDevMode();
  let ngComponentDef: any = null;
  // 元数据可能具有需要解析的资源
  maybeQueueResolutionOfComponentResources(type, metadata);
  // 这里使用的功能与指令相同,因为这只是创建 ngFactoryDef 所需的元数据的子集
  addDirectiveFactoryDef(type, metadata);
  Object.defineProperty(type, NG_COMP_DEF, {
    get: () => {
      if (ngComponentDef === null) {
        const compiler = getCompilerFacade();
        // 根据元数据解析组件
        if (componentNeedsResolution(metadata)) {
          ...
          // 异常处理
        }
        ...
        // 创建编译组件需要的完整元数据
        const templateUrl = metadata.templateUrl || `ng:///${type.name}/template.html`;
        const meta: R3ComponentMetadataFacade = {
          ...directiveMetadata(type, metadata),
          typeSourceSpan: compiler.createParseSourceSpan(&#39;Component&#39;, type.name, templateUrl),
          template: metadata.template || &#39;&#39;,
          preserveWhitespaces,
          styles: metadata.styles || EMPTY_ARRAY,
          animations: metadata.animations,
          directives: [],
          changeDetection: metadata.changeDetection,
          pipes: new Map(),
          encapsulation,
          interpolation: metadata.interpolation,
          viewProviders: metadata.viewProviders || null,
        };
        // 编译过程需要计算深度,以便确认编译是否最终完成
        compilationDepth++;
        try {
          if (meta.usesInheritance) {
            addDirectiveDefToUndecoratedParents(type);
          }
          // 根据模板、环境和组件需要的元数据,来编译组件
          ngComponentDef = compiler.compileComponent(angularCoreEnv, templateUrl, meta);
        } finally {
          // 即使编译失败,也请确保减少编译深度
          compilationDepth--;
        }
        if (compilationDepth === 0) {
          // 当执行 NgModule 装饰器时,我们将模块定义加入队列,以便仅在所有声明都已解析的情况下才将队列出队,并将其自身作为模块作用域添加到其所有声明中
          // 此调用运行检查以查看队列中的任何模块是否可以出队,并将范围添加到它们的声明中
          flushModuleScopingQueueAsMuchAsPossible();
        }
        // 如果组件编译是异步的,则声明该组件的 @NgModule 批注可以执行并在组件类型上设置 ngSelectorScope 属性
        // 这允许组件在完成编译后,使用模块中的 directiveDefs 对其自身进行修补
        if (hasSelectorScope(type)) {
          const scopes = transitiveScopesFor(type.ngSelectorScope);
          patchComponentDefWithScope(ngComponentDef, scopes);
        }
      }
      return ngComponentDef;
    },
    ...
  });
}

编译组件的过程可能是异步的(比如需要解析组件模板或其他资源的 URL)。如果编译不是立即进行的,compileComponent会将资源解析加入到全局队列中,并且将无法返回ɵcmp,直到通过调用resolveComponentResources解决了全局队列为止。

编译过程中的元数据

元数据是有关类的信息,但它不是类的属性。因此,用于配置类的定义和行为的这些数据,不应该存储在该类的实例中,我们还需要在其他地方保存此数据。

在 Angular 中,编译过程产生的元数据,会使用CompileMetadataResolver来进行管理和维护,这里我们主要看指令(组件)相关的逻辑:

export class CompileMetadataResolver {
  private _nonNormalizedDirectiveCache =
      new Map<Type, {annotation: Directive, metadata: cpl.CompileDirectiveMetadata}>();
  // 使用 Map 的方式来保存
  private _directiveCache = new Map<Type, cpl.CompileDirectiveMetadata>(); 
  private _summaryCache = new Map<Type, cpl.CompileTypeSummary|null>();
  private _pipeCache = new Map<Type, cpl.CompilePipeMetadata>();
  private _ngModuleCache = new Map<Type, cpl.CompileNgModuleMetadata>();
  private _ngModuleOfTypes = new Map<Type, Type>();
  private _shallowModuleCache = new Map<Type, cpl.CompileShallowModuleMetadata>();

  constructor(
      private _config: CompilerConfig, private _htmlParser: HtmlParser,
      private _ngModuleResolver: NgModuleResolver, private _directiveResolver: DirectiveResolver,
      private _pipeResolver: PipeResolver, private _summaryResolver: SummaryResolver<any>,
      private _schemaRegistry: ElementSchemaRegistry,
      private _directiveNormalizer: DirectiveNormalizer, private _console: Console,
      private _staticSymbolCache: StaticSymbolCache, private _reflector: CompileReflector,
      private _errorCollector?: ErrorCollector) {}
  // 清除特定某个指令的元数据
  clearCacheFor(type: Type) {
    const dirMeta = this._directiveCache.get(type);
    this._directiveCache.delete(type);
    ...
  }
  // 清除所有元数据
  clearCache(): void {
    this._directiveCache.clear();
    ...
  }
  /**
   * 加载 NgModule 中,已声明的指令和的管道
   */
  loadNgModuleDirectiveAndPipeMetadata(moduleType: any, isSync: boolean, throwIfNotFound = true):
      Promise<any> {
    const ngModule = this.getNgModuleMetadata(moduleType, throwIfNotFound);
    const loading: Promise<any>[] = [];
    if (ngModule) {
      ngModule.declaredDirectives.forEach((id) => {
        const promise = this.loadDirectiveMetadata(moduleType, id.reference, isSync);
        if (promise) {
          loading.push(promise);
        }
      });
      ngModule.declaredPipes.forEach((id) => this._loadPipeMetadata(id.reference));
    }
    return Promise.all(loading);
  }
  // 加载指令(组件)元数据
  loadDirectiveMetadata(ngModuleType: any, directiveType: any, isSync: boolean): SyncAsync<null> {
    // 若已加载,则直接返回
    if (this._directiveCache.has(directiveType)) {
      return null;
    }
    directiveType = resolveForwardRef(directiveType);
    const {annotation, metadata} = this.getNonNormalizedDirectiveMetadata(directiveType)!;
    // 创建指令(组件)元数据
    const createDirectiveMetadata = (templateMetadata: cpl.CompileTemplateMetadata|null) => {
      const normalizedDirMeta = new cpl.CompileDirectiveMetadata({
        isHost: false,
        type: metadata.type,
        isComponent: metadata.isComponent,
        selector: metadata.selector,
        exportAs: metadata.exportAs,
        changeDetection: metadata.changeDetection,
        inputs: metadata.inputs,
        outputs: metadata.outputs,
        hostListeners: metadata.hostListeners,
        hostProperties: metadata.hostProperties,
        hostAttributes: metadata.hostAttributes,
        providers: metadata.providers,
        viewProviders: metadata.viewProviders,
        queries: metadata.queries,
        guards: metadata.guards,
        viewQueries: metadata.viewQueries,
        entryComponents: metadata.entryComponents,
        componentViewType: metadata.componentViewType,
        rendererType: metadata.rendererType,
        componentFactory: metadata.componentFactory,
        template: templateMetadata
      });
      if (templateMetadata) {
        this.initComponentFactory(metadata.componentFactory!, templateMetadata.ngContentSelectors);
      }
      // 存储完整的元数据信息,以及元数据摘要信息
      this._directiveCache.set(directiveType, normalizedDirMeta);
      this._summaryCache.set(directiveType, normalizedDirMeta.toSummary());
      return null;
    };

    if (metadata.isComponent) {
      // 如果是组件,该过程可能为异步过程,则需要等待异步过程结束后的模板返回
      const template = metadata.template !;
      const templateMeta = this._directiveNormalizer.normalizeTemplate({
        ngModuleType,
        componentType: directiveType,
        moduleUrl: this._reflector.componentModuleUrl(directiveType, annotation),
        encapsulation: template.encapsulation,
        template: template.template,
        templateUrl: template.templateUrl,
        styles: template.styles,
        styleUrls: template.styleUrls,
        animations: template.animations,
        interpolation: template.interpolation,
        preserveWhitespaces: template.preserveWhitespaces
      });
      if (isPromise(templateMeta) && isSync) {
        this._reportError(componentStillLoadingError(directiveType), directiveType);
        return null;
      }
      // 并将元数据进行存储
      return SyncAsync.then(templateMeta, createDirectiveMetadata);
    } else {
      // 指令,直接存储元数据
      createDirectiveMetadata(null);
      return null;
    }
  }
  // 获取给定指令(组件)的元数据信息
  getDirectiveMetadata(directiveType: any): cpl.CompileDirectiveMetadata {
    const dirMeta = this._directiveCache.get(directiveType)!;
    ...
    return dirMeta;
  }
  // 获取给定指令(组件)的元数据摘要信息
  getDirectiveSummary(dirType: any): cpl.CompileDirectiveSummary {
    const dirSummary =
        <cpl.CompileDirectiveSummary>this._loadSummary(dirType, cpl.CompileSummaryKind.Directive);
    ...
    return dirSummary;
  }
}

可以看到,在编译过程中,不管是组件、指令、管道,还是模块,这些类在编译过程中的元数据,都使用Map来存储。

总结

本节我们介绍了 Angular 中的装饰器和元数据,其中元数据用于描述类的定义和行为。

在 Angular 编译过程中,会使用Map的数据结构来维护和存储装饰器的元数据,并根据这些元数据信息来编译组件、指令、管道和模块等。

更多编程相关知识,请访问:编程教学!!

위 내용은 Angular의 메타데이터와 데코레이터에 대해 이야기해 보겠습니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 juejin.cn에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제