NodeJS TypeError:无法读取未定义的属性(阅读'userService')

wbrvyc0a  于 2022-12-03  发布在  Node.js
关注(0)|答案(1)|浏览(219)

我收到错误

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

当试图访问我的类UserService的方法时,它却在另一个叫做ServicecenterController的类中。
首先,我在ServicecenterController中创建UserService类的一个示例。

export class ServicecenterController {
    private userService: UserService

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

然后我尝试访问ServicecenterController中的UserService方法。

const userOrgs = this.userService.getUserOrgsByEmail(email)

编译后,将发生TypeError

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)

任何帮助都是感激的,我对TypeScript/Node/Express相对较新
EDIT对于@Konrad的请求显示该函数的调用:行

const userOrgs = this.userService.getUserOrgsByEmail(email)

在方法async getCases()中被调用。此方法在

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)
    }

ServicecenterController的构造函数中调用

nqwrtyyt

nqwrtyyt1#

使用

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

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

相关问题