Hello I'm trying to create an application using express and es6 classes, but every time the class method is called this
is undefined.
UserController.js
export class UserController {
constructor() {
console.log('Class Constructed');
this.service = new UserService();
}
create(req, res, next) {
console.log('console', this);
this.service.create(req.body).then((user) => {
res.send(user);
});
}
}
route.js
import { Router } from 'express';
const router = Router();
router.route('/user/create')
.post(new UserController().create);
I noticed that when I execute npm run dev
, I got the console in the controller constructor, but when I call the '/user/create' from postman. I got TypeError: Cannot read property 'service' of undefined
.
Did I miss something? or is this kind of approach possible?
It would be great if someone can help me with this.
Thanks a lot.