bor*_*mke 3 decorator typescript ecmascript-2016
假设您有一个这样的类,并且Router附加了装饰器。
@Router
class AuthRouter {
constructor(private cacheService: CacheService) {}
}
Run Code Online (Sandbox Code Playgroud)
如何从Router装饰器中获取构造函数参数类型?假设我们已经存储了一个CacheService我们可以访问的单例,如果我们知道类名“CacheService”。
function Router(target) {
// somehow get the constructor class name
const dependencyNames = 'CacheService' // an array if multiple args in constructor
// getSingleton is a function that will retrieve
// a singleton of the requested class / object
return new target(getSingleton(dependencyNames))
}
Run Code Online (Sandbox Code Playgroud)
所以无论何时我们使用AuthRouter,它都会CacheService已经注入其中。
import 'reflect-metadata'
function Router(target) {
const types = Reflect.getMetadata('design:paramtypes', target);
// return a modified constructor
}
Run Code Online (Sandbox Code Playgroud)
请注意,您正在调用没有第三个参数的 getMetadata。types将是构造函数参数的数组。types[0].name === 'CacheService'在你的情况下。
| 归档时间: |
|
| 查看次数: |
2205 次 |
| 最近记录: |