gpt4 book ai didi

angular - @Component 装饰器究竟做了什么?

转载 作者:太空狗 更新时间:2023-10-29 17:25:14 26 4
gpt4 key购买 nike

来自 official docs我们知道

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.

但我想更深入地了解 Component decorator 除了提供额外的元数据之外的真正作用。

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

就像一个答案,如果能一步一步地描述我应该如何在没有 makeDecorator 函数的情况下重新创建组件装饰器,那就太好了。

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

最佳答案

But I would like to go deeper and understand what Component decorator really does except providing additional metadata.

为什么还需要更多?据说传递给 @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 - @Component 装饰器究竟做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40983890/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com