简体   繁体   English

@Component装饰器到底做了什么?

[英]What does @Component decorator exactly do?

From official docs we know that 官方文档我们知道

Component decorator allows you to mark a class as an Angular component and provide additional metadata that determines how the component should be processed, instantiated and used at runtime. 组件装饰器允许您将类标记为Angular组件,并提供其他元数据,以确定如何在运行时处理,实例化和使用组件。

But I would like to go deeper and understand what Component decorator really does except providing additional metadata. 但我想更深入地了解组件装饰器除了提供额外的元数据之外真正做了什么。

I dived into source code and found that all decorators are created with help of makeDecorator function. 我潜入了源代码,发现所有装饰器都是在makeDecorator函数的帮助下创建的。 And here I got lost. 在这里,我迷路了。 Where is the difference for example for Component and ngModule decorators? Component和ngModule装饰器的示例区别在哪里? Are they doing the same thing? 他们做同样的事吗? Don't think so. 不要这么认为。

Like an answer it would be great to have step by step description what I should do to recreate Component Decorator without makeDecorator function. 就像一个答案一样,如果没有makeDecorator函数重新创建Component Decorator,我需要一步一步地描述我应该做些什么。

UPD : and, Yes, of course, I know how TypeScript Decorators work. UPD :是的,当然,我知道TypeScript Decorators是如何工作的。

But I would like to go deeper and understand what Component decorator really does except providing additional metadata. 但我想更深入地了解组件装饰器除了提供额外的元数据之外真正做了什么。

Why does it need to be anything more? 为什么还需要更多? It's said that the argument passed to the @Component decorator function is the component metatdata . 据说传递给@Component装饰器函数的参数是元素metatdata So that is the main responsibility, to provide metadata. 因此,提供元数据是主要责任。

The easiest way, if you want to reproduce something similar is to 最简单的方法,如果你想重现类似的东西是

  1. Install the reflect-metadata . 安装reflect-metadata

     npm install --save reflect-metadata 
  2. Create the decorator function 1 创建装饰器功能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. Use it 用它

     @MyComponent({ selector: 'component', template: '<hello></hello>' }) class HelloComponent { } 
  4. Now when you need to get the metadata, just do 现在,当您需要获取元数据时,就这样做

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

The purpose of the metadata is to provide information for Angular to know what to do with the class. 元数据的目的是为Angular提供信息,以便知道如何处理该类。 So the decorator doesn't really need to be anything more than just a metadata provider. 因此,装饰器实际上不需要只是元数据提供者。 Angular decides what to do with the metadata, not the decorator function. Angular决定如何处理元数据,而不是装饰器功能。


1 - See TypeScript documentation on decorators 1 - 请参阅装饰器上的TypeScript文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM