无法在方法上定义或检索元数据



我试图将元数据键值对附加到对象键(TS类中的方法(,但实际上没有对元素执行任何操作。

import 'reflect-metadata';
export const get = (path: string) => (target: any, key: string, desc: PropertyDescriptor) => {
Reflect.defineMetadata('path', path, target, key);
console.log(`path, target, key -> ${ path }, ${ target }, ${ key }`);
};

代码中调用部分的代码段

@controller('/auth')
export class LoginController {
@get('/login')
getLogin(req: Request, res: Response): void {/* method implementation */};
}

控制器迭代方法元数据

export const controller = (routePrefix: string) => {
return function (target: Function) {
for (let key in target.prototype) {
const routeHandler = target.prototype[key];
const path = Reflect.getMetadata('path', target.prototype[key]);
console.log('here is the path! -> ' + path);
if (path)
router.get(`${ routePrefix }${ path }`, routeHandler);
}
};
};

"调试";信息

// Output
// [start:dev] path, target, key -> /login, [object Object], getLogin
// [start:dev] here is the path! -> undefined

好的,解决了。我向Reflect.getMetadata方法传递了错误的参数。

Reflect.getMetadata('path', target.prototype, key);

而不是

Reflect.getMetadata('path', target.prototype[key]); // Wrong!

最新更新