typescript装饰程序如何允许angular 2发现类型元数据
我不明白typescript装饰器typescript装饰程序如何允许angular 2发现类型元数据,angular,typescript,typescript2.0,Angular,Typescript,Typescript2.0,我不明白typescript装饰器@Injectable是如何捕获类型信息的,以及当构造函数参数列表中没有提供显式@injecte(…)时,它以后如何知道哪个构造函数参数对应于哪个类型?如何复制这种行为,简单地说,为我自己的库创建我自己的注入器 @Injectable() export class AppService { } export class AppComponent { public constructor(private appService: AppService) {
@Injectable
是如何捕获类型信息的,以及当构造函数参数列表中没有提供显式@injecte(…)
时,它以后如何知道哪个构造函数参数对应于哪个类型?如何复制这种行为,简单地说,为我自己的库创建我自己的注入器
@Injectable()
export class AppService {
}
export class AppComponent {
public constructor(private appService: AppService) {
}
}
例如,您可以在编译后的代码中看到有关装饰器如何工作的细节 编译后的代码如下所示
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);
当angular core对此进行研究时,它使用Reflect.js
获取有关组件的元数据信息
要创建自己的装饰器,您可以在下面尝试
MyCustomDecorator
import "reflect-metadata";
interface ICustomDecoratorMeta{
var1: string
}
export var MyCustomDecorator =
(metadata: <ICustomDecoratorMeta>) => {
return (target) => {
Reflect.defineMetadata("MyCustomDecorator", metadata, target);
}
}
希望这有帮助
@MyCustomDecorator({
var1 : "Hello"
})
export class MyClass(){}
// To retrieve metadata you can use below,
var metadata = Reflect.getMetadata('MyCustomDecorator', MyClass);