Ale*_*Dim 3 javascript this node.js es6-class nestjs
我有一个具有 monorepo 结构的 NestJS 项目,并且在this和 方面面临困难context。
我有一个应用程序文件:和一个通过Nest CLIapp.service.ts生成的内部库。
有以下代码逻辑: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);
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题如上所示。我在类服务中有一个函数方法,是在 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);
});
}
Run Code Online (Sandbox Code Playgroud)
有几种方法,第一个解决方案是在构造函数中使用bindyow方法ProblemSave
export class AppService {
constructor () {
this.ProblemSave = this.ProblemSave.bind(this);
}
ProblemSave () {
//stuff
}
}
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是使用箭头函数而不是方法
export class AppService {
constructor () {}
ProblemSave = () => {
//stuff
}
}
Run Code Online (Sandbox Code Playgroud)