访问元注释内部类(打字稿) [英] Access Meta-Annotation inside Class (TypeScript)

查看:169
本文介绍了访问元注释内部类(打字稿)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我注释一类的打字稿,例如元创建Angular2组成部分,我可以访问类中的元数据?

 进口{}组件从angular2 /核心;@零件({
    选择:应用程序,
    templateUrl:/app/components/app/app.component.html
})
出口类AppComponent {    //我可以访问templateUrl从上面的注释吗?}


解决方案

您可以看到一个标注/装饰作为一个普通的函数调用。这个函数的类/函数对象(不是实例)中获得的第一个参数发送,并在第二个参数的参数(元数据)。

但是这取决于该函数的实现有什么东西被添加为实例类(不好的做法/揭露属性)的雏形。打字稿编译器和Angular2做的事情,虽然是不同的。

他们用 __装饰 __元的功能,这是由打字稿编译器生成。这些数据与<一个被添加href=\"https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\">Object.defineProperty()功能。负责这一包是反映。 (其中引擎盖下使用 Object.defineProperty()函数与组合 WeakMap )。

功能 Reflect.defineMetadata()用于设置注解,并获得他们明显 Reflect.getMetadata()

TLDR;


  • 要在angular2类/组件得到注解,你有
    使用方法:

      Reflect.getMetadata('注释',ComponentClass); // @组分({}),@Pipe({}),...


  • 要获得在angular2构造PARAMATERS注解,你必须使用:

      Reflect.getMetadata('参数',ComponentClass); //@注入()


  • 要得到一个属性标注在一个类中angular2,你
    要使用:

      Reflect.getMetadata('propMetadata',ComponentClass); // @ HostBinding(),@input(),...


When I annotate a class with metadata in TypeScript, e.g. to create an Angular2 component, can I access the metadata inside that class?

import {Component} from 'angular2/core';

@Component({
    selector: 'app',
    templateUrl: '/app/components/app/app.component.html'
})
export class AppComponent {

    // can I access 'templateUrl' from above annotation here?

}

解决方案

You can see an annotation/decorator as a normal function call. To this function the 'Class/Function' object (not instance) gets send in the first parameter, and the parameters (metadata) in the second argument.

However it depends on the implementation of that function if something gets added for instance to the prototype of the class (bad practice/exposing property). The TypeScript compiler and Angular2 do things differently though.

They use the __decorate and __metadata functions, which are generated by the TypeScript compiler. The data gets added with the Object.defineProperty() function. The package responsible for this is Reflect. (which under the hood uses the Object.defineProperty() function in combination with a WeakMap).

The function Reflect.defineMetadata() is used to set the annotations, and to obtain them the obvious Reflect.getMetadata().

TLDR;

  • To get the annotations from a class/component in angular2, you have to use:

    Reflect.getMetadata('annotations', ComponentClass); //@Component({}), @Pipe({}), ...
    

  • To get the annotations from the constructor paramaters in angular2, you have to use:

    Reflect.getMetadata('parameters', ComponentClass); //@Inject()
    

  • To get the annotations from a property in a class in angular2, you have to use:

    Reflect.getMetadata('propMetadata', ComponentClass); //@HostBinding(), @Input(), ...
    

这篇关于访问元注释内部类(打字稿)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆