Problem with undefined value in class function when passing though express router

36 views Asked by At

I have a simple class in node 8 but having an issue with this value.

module.exports = class Controller {
    constructor() {
        this.service = new Service();
    }
    create(request, response, next) {
        try {
            const body = request.body;
            this.service.create(body)
            console.log(this.service)// Undefined
        } catch (error) {
        next(error)
    }

The problem which I'm having is this value is undefined. A controller above is trigger by the router:

const Router = require("express").Router;
const Controller = require("./controller");

module.exports = class NewRouter {
    constructor() {
        this.router = new Router();
        this.controller = new Controller();
        this.initRoutes();
    }
    initRoutes() {
        this.router.post("/setup", this.controller.create);
    }
};
1

There are 1 answers

0
MarJano On

I think I sorted the problem but really don't like the solution

this.router.post("/setup", this.controller.create.bind(this.controller));