javascript - NestJS losing context of this inside function method in service class - Stack Overflow

I have a nestJS project with a monorepo structure and face difficulties with this and context.I have a

I have a nestJS project with a monorepo structure and face difficulties with this and context.

I have an app file: app.service.ts and an inner lib generated via Nest CLI. app.services.ts has the following code logic:

//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);
  }

So my problem is shown above. I have a functional method inside class service, created in Nest, which is called as a function inside another method. But somehow in one case, this inside class methods works fine. But if I pass it in another method, the context of this lost and my function fails, with this.LibService is undefined error.

What should I do to solve the problem?

The listener code is below if someone is interested.

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);
    });
}

I have a nestJS project with a monorepo structure and face difficulties with this and context.

I have an app file: app.service.ts and an inner lib generated via Nest CLI. app.services.ts has the following code logic:

//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);
  }

So my problem is shown above. I have a functional method inside class service, created in Nest, which is called as a function inside another method. But somehow in one case, this inside class methods works fine. But if I pass it in another method, the context of this lost and my function fails, with this.LibService is undefined error.

What should I do to solve the problem?

The listener code is below if someone is interested.

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);
    });
}
Share Improve this question edited Apr 4, 2021 at 15:17 AlexZeDim asked Apr 4, 2021 at 15:06 AlexZeDimAlexZeDim 4,3724 gold badges34 silver badges77 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

there are couple of ways, first solution is to bind yow ProblemSave method in the constructor

export class AppService {

  constructor () {
    this.ProblemSave = this.ProblemSave.bind(this);
  }

   ProblemSave () {
     //stuff
   }
}

another solution is to use them arrow functions instead of methods

export class AppService {

  constructor () {}

   ProblemSave  = () => {
     //stuff
   }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745340821a4623317.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信