Home > Software design >  TypeError: Cannot read properties of undefined (reading 'userService')
TypeError: Cannot read properties of undefined (reading 'userService')

Time:12-02

I get the error

TypeError: Cannot read properties of undefined (reading 'userService')

while trying to access a method of my class UserService in another class called ServicecenterController.

At first, i create an instance of the class UserService in the ServicecenterController

export class ServicecenterController {
    private userService: UserService

    constructor(...) {
        ...
        this.userService = new UserService()
        this.initRoutes()
    }

Then i try to access a method of UserService in the ServicecenterController

const userOrgs = this.userService.getUserOrgsByEmail(email)

After compiling, the TypeError will occur

TypeError: Cannot read properties of undefined (reading 'userService')
    at ...\src\controllers\servicecenter.controller.ts:81:35
    at Generator.next (<anonymous>)
    at ...\src\controllers\servicecenter.controller.ts:8:71
    at new Promise (<anonymous>)
    at __awaiter (...\src\controllers\servicecenter.controller.ts:4:12)
    at getCases (...\src\controllers\servicecenter.controller.ts:78:16)
    at Layer.handle [as handle_request] (...\node_modules\express\lib\router\layer.js:95:5)
    at next (...\node_modules\express\lib\router\route.js:144:13)
    at middleware (...\node_modules\express-validator\src\middlewares\check.js:16:13)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

Any help is appreciated, i am relatively new to TypeScript/Node/Express

EDIT For @Konrad 's request to show the call of that function: The line

const userOrgs = this.userService.getUserOrgsByEmail(email)

gets called in the method async getCases(). This method again gets called in

private initRoutes(){
        this.router.get('/', this.validationService.validateRequest('getDevices'), this.getCases)
        this.router.get('/latest', this.validationService.validateRequest('getDevices'), this.getLatestCases)
        this.router.post('/create', this.createCase)
    }

which is called in the constructor of ServicecenterController

CodePudding user response:

Either use

this.router.get('/', this.validationService.validateRequest('getDevices'), this.getCases.bind(this))

or

this.router.get('/', this.validationService.validateRequest('getDevices'), () => this.getCases())
  • Related