I’m trying to get this.appConstantsService
inside of FileService
. But the problem is when executing method this
is undefined. All my application uses the same code style, and I can’t figure out, why methods of this class lose this
, while others, in other classes, work fine?
Simplified code:
@Injectable()
export class FileService implements OnModuleInit, OnModuleDestroy {
constructor(private readonly appConstantsService: AppConstantsService) {
console.log(this.appConstantsService); // => ok, it shows env variables.
}
onModuleDestroy() {
console.log("FileService destroy!"); // => it doesn't - fine
}
onModuleInit(): any {
console.log("FileService init!"); // => ok
}
normalize(file: File): TFileToClient {
const f = excludeSensitiveFields(file, [
"path",
"size",
]) as TFileToClient;
console.log(this); // => undefined
f.url =
/*
* ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'appConstantsService')
* */
this.appConstantsService.BACKEND_URL +
"/api/s3/file/" +
file.originalName +
"?path=" +
file.path;
f.size = byteSize({
sizeInBytes: file.size,
});
return f;
}
}
Although I think it doesn’t matter, but both AppConstantsService and DatabaseService are @Global. And they are available in other classes. But, that’s not the point, because my problem is that this
keyword is undefined
.
I could understand if I was trying to pass the “this” keyword inside another function, but I didn’t do that.
So, I spent a lot of time trying to find the answer, but I couldn’t. And I just tried to use the arrow method instead – and it also functions great.
But this.normalize.bind(this)
in constructor couldn’t help.
Changed code:
@Injectable()
export class FileService implements OnModuleInit, OnModuleDestroy {
constructor(private readonly appConstantsService: AppConstantsService) {
console.log(this.appConstantsService); // => ok, it shows env variables.
}
onModuleDestroy() {
console.log("FileService destroy!"); // => it doesn't - fine
}
onModuleInit(): any {
console.log("FileService init!"); // => ok
}
normalize = (file: File): TFileToClient => {
const f = excludeSensitiveFields(file, [
"path",
"size",
]) as TFileToClient;
f.url =
/*
* now it works
* */
this.appConstantsService.BACKEND_URL +
"/api/s3/file/" +
file.originalName +
"?path=" +
file.path;
f.size = byteSize({
sizeInBytes: file.size,
});
return f;
};
}
How is it possible? All my methods in other services use only trivial methods, not arrow methods, and this
keyword is not lost.
Thanks for your answers