Currently, I am in the process of developing a MERN Application using Typescript.
I seem to be encountering an issue with this within my class.
When utilizing this code snippet:
router.post("/create", user.createNewUser);
It becomes impossible to call another method from the class user inside the function createNewUser.
However, when using the following snippet instead:
router.post("/create", (req: Request, res: Response, next: NextFunction) => {
try {
user.createNewUser(req, res, next);
} catch (error) {
res.json(error);
}
});
It functions correctly.
This is the createNewUser function:
createNewUser(req: Request, res: Response, next: NextFunction) {
try {
const { password, username, email, id } = req.body;
const payload: object = { /* HERE MY JSON */ };
schema.create(payload, async(err: any, result: any) => {
const isSended = await this.sendRegistrationEmail(email);
if (err) throw err;
if (isSended) {
res.status(200).json(result);
} else {
res.status(500).json('error');
}
});
} catch (error) {
res.status(500).send(error);
}
};
The encountered error message is:
TypeError: Cannot read property 'sendRegistrationEmail' of undefined
I am curious as to why the first solution does not work while the second one does.