How does typescript decorators allow angular 2 to discover type metadata -
i don't understand how typescript decorator @injectable
captures type information , how later knows constructor parameter corresponds type when no explicit @inject(...)
provided within constructor parameter list? how replicate such behavior , in simple terms create own injector own library.
@injectable() export class appservice { } export class appcomponent { public constructor(private appservice: appservice) { } }
you may see insight within compiled code on how decorators works, example
compiled code looks below,
componentclass = __decorate([ core_1.component({ moduleid: module.id, selector: 'component-selector', templateurl: 'component.html', styleurls: ['component.css'], providers: [component_service_1.componentservice] }), __metadata('design:paramtypes', [component_service_1.componentservice]) ], componentclass);
when angular core looks uses reflect.js
metadata info component.
to create own decorator, can try below,
mycustomdecorator
import "reflect-metadata"; interface icustomdecoratormeta{ var1: string } export var mycustomdecorator = (metadata: <icustomdecoratormeta>) => { return (target) => { reflect.definemetadata("mycustomdecorator", metadata, target); } }
how use it,
@mycustomdecorator({ var1 : "hello" }) export class myclass(){} // retrieve metadata can use below, var metadata = reflect.getmetadata('mycustomdecorator', myclass);
hope helps!!
Comments
Post a Comment