NodeJS TypeError:使用express时无法读取未定义的属性

rwqw0loc  于 9个月前  发布在  Node.js
关注(0)|答案(1)|浏览(120)

我遇到了一个我无法理解的问题,我以前写过同样结构的代码,从来没有遇到过这个问题,所以我真的很难理解这里发生了什么。
我有这三个文件:
index.ts

import { Controller } from "./controller";
import express from "express";

const app = express();

const controller = new Controller();

app.use("/api", controller.router);

app.listen(3000, () => console.log("listening"));

字符串
controller.ts

import { Router } from "express";
import { Service } from "./service";

export class Controller {
  router = Router();

  private service = new Service();

  constructor() {
    this.router.get("/all", this.getAll);
  }

  getAll() {
    console.log("getAll");

    this.service.findAll(); // problem here
  }
}


service.ts

export class Service {
  findAll() {
    console.log("findAll");
  }
}


如果我尝试在index.ts上调用controller.getAll(),一切都会按照预期进行:函数getAll()被调用,然后findAll()在getAll()内部被调用。
问题是,当我尝试对localhost:3000/api/all执行GET请求时,getAll()会正常调用,但当到达this.service.findAll()时,会发生以下错误:

TypeError: Cannot read properties of undefined (reading 'service')
    at getAll (/home/user/personal/test/src/controller.ts:16:22)


相关性:

"devDependencies": {
    "@types/express": "^4.17.21",
    "ts-node": "^10.9.2"
  },
  "dependencies": {
    "express": "^4.18.2"
  }

k4ymrczo

k4ymrczo1#

问题出在将getAll绑定到路由的那一行。传递this.getAll最终导致this引用的上下文出现问题。这就是导致您看到的错误的原因,其中this未定义。
解决这个问题的一个简单方法是声明一个内联箭头函数,如下所示。

constructor() {
    this.router.get("/all", () => this.getAll());
  }

字符串
MDN Reference

相关问题