2

我不明白 typescript 装饰器如何捕获类型信息,以及当构造函数参数列表中@Injectable没有提供显式时,它如何知道哪个构造函数参数对应于哪个类型?@Inject(...)如何复制这种行为,简单来说,为我自己的库创建我自己的注入器。

@Injectable()
export class AppService {
}

export class AppComponent {
    public constructor(private appService: AppService) {

    }
}
4

1 回答 1

2

您可能会在编译后的代码中看到有关装饰器如何工作的见解,例如

编译后的代码如下所示,

    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);

当角度核心对此进行调查时,它用于Reflect.js获取有关组件的元数据信息。

要创建自己的装饰器,您可以在下面尝试,

我的自定义装饰器

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);

希望这可以帮助!!

于 2016-09-07T15:15:45.163 回答