【发布时间】:2021-06-30 16:52:44
【问题描述】:
我有一个带有 monorepo 结构的 nestJS 项目,并且在使用 this 和 context 时遇到了困难。
我有一个应用文件: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