关于类装饰器和元数据的问题
Author: zyhcoolCreated Oct 11, 2019Updated Jan 18, 2023
有个疑问请教各位: 在这篇文章此处有段代码:
type Constructor<T = any> = new (...args: any[]) => T;
const Injectable = (): ClassDecorator => target => {};
class OtherService {
a = 1;
}
@Injectable()
class TestService {
constructor(public readonly otherService: OtherService) {}
testMethod() {
console.log(this.otherService.a);
}
}
const Factory = <T>(target: Constructor<T>): T => {
// 获取所有注入的服务
const providers = Reflect.getMetadata('design:paramtypes', target); // [OtherService]
const args = providers.map((provider: Constructor) => new provider());
return new target(...args);
};
Factory(TestService).testMethod(); // 1
其中 Injectable 装饰器实质上并没有对 TestService 类进行修改,那为什么这边还要加上这个类装饰器呢?
实验证明,如果不加上的话,Reflect.getMetadata('design:paramtypes', target) 将无效,这是为什么呢?
谢谢解答!
Source: jkchao/typescript-book-chinese