I have an express.js application that uses the express.Router()
to connect my endpoints to controllers.
My goal is to have an object newed up in the controller constructor so I can use it in all controller functions without having to new it up in each one.
The constructor runs correct, and the object is available within the constructor. But whenever I call any actions of the controller, the object is null.
Here is the router
const express = require('express');
const componentController = require('../controllers/component');
const router = express.Router();
// component routes
router.get('/components', componentController.getComponents);
module.exports = router;
And here is my controller.
const LogService = require('../services/logService');
class ComponentController {
constructor() {
this.logger = new LogService('ComponentController');
this.logger.logDebug('test1','test1');
}
async getComponents(req, res) {
const test = new LogService('ComponentController');
test.logDebug('test2','test2');
this.logger.logDebug('test3','test3')
res.json('');
}
}
module.exports = new ComponentController();
I want the LogService to be available in the controller actions. The first two logs work correctly, test1
and test2
. But test3
throws an error saying logger is undefined.
Why is this.logger
undefined in later functions? How can I fix this issue?
CodePudding user response:
try to refactor getComponents
to an arrow function.
Here is why: https://javascript.plainenglish.io/this-binding-in-es6-arrow-function-70d80e216238
You can also do this:
router.get('/components', componentController.getComponents.bind(componentController));