【问题标题】:What does @Component decorator exactly do?@Component 装饰器到底做了什么?
【发布时间】:2017-04-20 09:57:27
【问题描述】:

official docs我们知道

组件装饰器允许您将类标记为 Angular 组件,并提供额外的元数据来确定组件在运行时应如何处理、实例化和使用。

但我想更深入地了解组件装饰器的真正作用,除了提供额外的元数据。

我深入研究了源代码,发现所有装饰器都是在makeDecorator 函数的帮助下创建的。在这里我迷路了。例如 Component 和 ngModule 装饰器的区别在哪里?他们在做同样的事情吗?不要这么认为。

就像一个答案一样,我应该逐步描述我应该如何在没有 makeDecorator 函数的情况下重新创建组件装饰器。

UPD:当然,我知道 TypeScript 装饰器是如何工作的。

【问题讨论】:

    标签: angular angular2-components angular2-decorators


    【解决方案1】:

    但我想更深入地了解组件装饰器的真正作用,除了提供额外的元数据。

    为什么还需要更多?据说传递给@Component 装饰器函数的参数是组件metatdata。因此,提供元数据是主要责任。

    如果你想重现类似的东西,最简单的方法是

    1. 安装reflect-metadata

      npm install --save reflect-metadata
      
    2. 创建装饰器函数1

      import 'reflect-metadata';
      
      interface MyComponentMetadata {
        template?: string;
        selector?: string;
      }
      
      function MyComponent(metadata: MyComponentMetadata) {
        return function(ctor: Function) {
          // add metadata to constructor
          Reflect.defineMetadata('annotations', metadata, ctor);
        }
      }
      
    3. 使用它

      @MyComponent({
        selector: 'component',
        template: '<hello></hello>'
      })
      class HelloComponent {
      }
      
    4. 现在,当您需要获取元数据时,只需这样做

      let metadata = Reflect.getMetadata('annotations', HelloComponent);
      

    元数据的目的是为 Angular 提供信息以了解如何处理该类。所以装饰器实际上并不需要仅仅是一个元数据提供者。 Angular 决定如何处理元数据,而不是装饰器函数。


    1 - 见TypeScript documentation on decorators

    【讨论】:

    • 仅供参考:在我的@angular/cli@1.2.1 项目中,我必须在main.ts 文件的顶部导入reflect-metadata,以使编译器知道defineMetadatagetMetadata职能。在我的装饰器源文件中进行导入导致编译器抱怨缺少 @NgModule 装饰器。
    猜你喜欢
    • 2019-10-02
    • 2022-11-10
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 2011-12-10
    • 2016-10-26
    相关资源
    最近更新 更多