NestJS 在服务中丢失此内部函数方法的上下文 class
NestJS losing context of this inside function method in service class
我有一个带有 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);
}
所以我的问题如上所示。我在 class 服务中有一个功能方法,它是在 Nest 中创建的,它在另一个方法中被称为函数。但不知何故,在一种情况下,class 方法中的 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);
});
}
有几种方法,第一个解决方案是 bind
yow ProblemSave
构造函数中的方法
export class AppService {
constructor () {
this.ProblemSave = this.ProblemSave.bind(this);
}
ProblemSave () {
//stuff
}
}
另一个解决方案是使用箭头函数而不是方法
export class AppService {
constructor () {}
ProblemSave = () => {
//stuff
}
}
我有一个带有 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);
}
所以我的问题如上所示。我在 class 服务中有一个功能方法,它是在 Nest 中创建的,它在另一个方法中被称为函数。但不知何故,在一种情况下,class 方法中的 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);
});
}
有几种方法,第一个解决方案是 bind
yow ProblemSave
构造函数中的方法
export class AppService {
constructor () {
this.ProblemSave = this.ProblemSave.bind(this);
}
ProblemSave () {
//stuff
}
}
另一个解决方案是使用箭头函数而不是方法
export class AppService {
constructor () {}
ProblemSave = () => {
//stuff
}
}