Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

angular - Access Meta-Annotation inside Class (TypeScript)

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?

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With the new angular version, you should use the native Reflect object. No IE11 support though:

const annotations = Reflect.getOwnPropertyDescriptor(MyModule, '__annotations__').value;

Read Jeff Fairley's answer below on what to do with the data after that

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(), ...
    


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...