【问题标题】:NestJS losing context of this inside function method in service classNestJS 在服务类中丢失了 this 内部函数方法的上下文
【发布时间】:2021-06-30 16:52:44
【问题描述】:

我有一个带有 monorepo 结构的 nestJS 项目,并且在使用 thiscontext 时遇到了困难。

我有一个应用文件:app.service.ts 和一个通过 Nest CLI 生成的内部库。 app.services.ts的代码逻辑如下:

//import dependencies

@Injectable()
export class AppService implements OnApplicationBootstrap {
  private readonly logger = new Logger('SomeName');

  private readonly ENV_VARIABLE = config.from();

  private ws: WebSocket;

  constructor(
    @InjectRepository(RowEntity) //Repository from TypeORM
    private readonly postgresRepository: Repository<RowEntity>,
    private readonly otherService: LibService, // import from @app/lib
  ) {}

  async onApplicationBootstrap(): Promise<void> {
    await this.loadInitial();
  }

  async loadInitial() {
    this.ws = new WebSocket(url); // standart web socket connection

    const connection = new this.ws() // connection works fine

    addListener(connection, this.logger, this.ProblemSave);  //such as Listener

    /**
     * BUT! 
     * await this.LibService.getMethod(input.toLowerCase()); 
     * works well here!
     */
  }

  async ProblemSave(input: string) {
    /**
     * PROBLEM HERE!
     * NestJS losing context of this keyword when executing via Listener
     */
    const data = await this.LibService.getMethod(input.toLowerCase()); // drops with error, since this undefined
    console.log(data);
    await this.postgresRepository.save(data);
  }

所以我的问题如上所示。我在类服务中有一个函数方法,在 Nest 中创建,它在另一个方法中作为函数调用。但在某种情况下,this 内部类方法工作正常。但是如果我用另一种方法传递它,this 的上下文会丢失,我的函数会失败,this.LibService is undefined 错误。

我应该怎么做才能解决这个问题?

如果有人感兴趣,下面是监听器代码。

export function addListener(
  connection: connectionInterface,
  logger: Logger,
  saveFunc: FunctionInterface,
): void {
  connection.events({}, async (error: ErrnoException, {
    returnValues,
  }: {
    returnValues: ObjectInterface
  }) => {
    if (error) {
      logger.log(error);
      return;
    }

    try {

      //Execution works fine, but fails, because saveFunction doesn't have this context
      await saveFunc({
        input
      });

      logger.log(`Event created with id ${id}`);
      return;
    } catch (e) {
      console.error('ERROR', e);
      logger.log(e);
    }
  })
    .on('connected', (subscriptionId: string) => {
      logger.log(`subscribed to events with id ${subscriptionId}`);
    })
    .on('error', (error: ErrnoException) => {
      logger.log('error');
      logger.log(error);
    });
}

【问题讨论】:

    标签: javascript node.js this nestjs es6-class


    【解决方案1】:

    有几种方法,第一个解决方案是构造函数中的bind yow ProblemSave 方法

    export class AppService {
    
      constructor () {
        this.ProblemSave = this.ProblemSave.bind(this);
      }
    
       ProblemSave () {
         //stuff
       }
    }
    

    另一种解决方案是使用箭头函数而不是方法

    export class AppService {
    
      constructor () {}
    
       ProblemSave  = () => {
         //stuff
       }
    }
    

    【讨论】:

    • 感谢您向我澄清这一点,但我似乎在白天失去了理智。我用箭头=&gt;函数。
    猜你喜欢
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2020-09-18
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 2016-06-02
    相关资源
    最近更新 更多