gpt4 book ai didi

javascript - NestJS 在服务类中丢失此内部函数方法的上下文

转载 作者:行者123 更新时间:2023-12-04 07:51:37 25 4
gpt4 key购买 nike

我有一个带有 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);
});
}

最佳答案

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

export class AppService {

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

ProblemSave () {
//stuff
}
}

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

export class AppService {

constructor () {}

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

关于javascript - NestJS 在服务类中丢失此内部函数方法的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66942658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com