0

我正在尝试将元数据键值对附加到对象键(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
4

1 回答 1

0

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

它是

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

代替

Reflect.getMetadata('path', target.prototype[key]); // Wrong!
于 2020-10-29T14:49:46.900 回答