亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

裝飾器在任何其他混亂“this”上下文之前調用方法

裝飾器在任何其他混亂“this”上下文之前調用方法

天涯盡頭無女友 2023-07-06 19:56:02
真正的問題我想我找到了真正的問題,inversify其他一切都很好。在原來的帖子中,我省略了部分代碼,因為我認為它們不是造成問題的原因。在我的ICitiesRepo實現中,我有一個方法ensureDb確保初始化一些typeorm屬性,因為這個方法必須是異步的,我不能只在構造函數中調用它,所以應該在任何 CRUD 操作之前調用它,然后我創建了一個具有以下目的的裝飾器ensureDb在類中的任何其他方法之前調用:  export const ensureCall = (method: string) => {    return (target: any) => {      for (const prop of Object.getOwnPropertyNames(target.prototype)) {        if (prop === method || prop === 'constructor') continue;        const originalMethod = target.prototype[prop];        if (originalMethod instanceof Function) {          target.prototype[prop] = async (...args: any[]) => {            await target.prototype[method]();            return originalMethod.apply(this, args);          };        }      }    };  };這就是用途:   @ensureCall('ensureDb')   @injectable()   class CitiesRepo implements ICitiesRepo {       @inject('CitiesWriteRepo') private readonly repo: IWriteRepo<City>;              async ensureDb() {          await this.repo.doSomething();          // repo is undefined because I messed up with the context       }          // interface implementation   }ensureDb如果我刪除該裝飾器并在其他方法之前調用它就可以工作:   const container = getContainer();   const citiesRepo: ICitiesRepo = container.get('CitiesRepo');   await citiesRepo.ensureDb();   const list = await citiesRepo.getAll(); // It works是否有可能解決這個問題或其他更好的方法來實現我想做的事情?原帖我有一個帶有通用存儲庫的項目,但在使用 inversifyJS 注入存儲庫對象時遇到一些問題。結構是這樣的:   interface IWriteRepo<T>  { /* interface members */ }   @injectable()   class WriteRepo<City> implements IWriteRepo<City> { /* interface implementation */ }   interface ICitiesRepo { /* interface members */ }   @injectable()   class CitiesRepo implements ICitiesRepo {       @inject('CitiesWriteRepo') private readonly repo: IWriteRepo<City>;       // interface implementation   }該服務已正確注入,repo: ICitiesRepo但通用“孫子”repo: IWriteRepo<City>未定義。知道如何修復它嗎?
查看完整描述

1 回答

?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

你快到了。你之所以得到這個,是undefined因為this你的裝飾器中是未定義的,應該引用你的目標的實例化實例。將該定義更改為常規函數調用而不是箭頭函數應該可以解決問題。


export const ensureCall = (method: string) => {

  return (target: any) => {

    for (const prop of Object.getOwnPropertyNames(target.prototype)) {

      if (prop === method || prop === 'constructor') continue;


      const originalMethod = target.prototype[prop];

      if (originalMethod instanceof Function) {

        // Regular function declaration

        target.prototype[prop] = async function(...args: any[]) {

          await target.prototype[method]();

          // Now `this` refers to an instantiated instance

          return originalMethod.apply(this, args);

        };

      }

    }

  };

};


查看完整回答
反對 回復 2023-07-06
  • 1 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號