我在TypeScript中有这个类,当我调用this.unitService
时,我收到错误。
controller.ts
import { Request, Response } from "express";
import Unit from "../models/unit.model";
import Relation from "../models/relation.model";
import { TypeRelation } from "../models/typeralation.enum";
import { UnitService } from "../services/unit.service";
export class HomeController {
unitService: UnitService = new UnitService();
constructor() { }
forceCreateUnit(req: Request, res: Response): void {
const unit = "{ type: " + TypeRelation.USE + ", topUnit: new ObjectId(\"5adf231d85dded040f3f6d03\"), lowerUnit: new ObjectId(\"5adf231d85dded040f3f6d03\")}";
this.unitService.prueba();
res.send("OK");
}
}
unit.service.ts
import Relation from "../models/relation.model";
import { TypeRelation } from "../models/typeralation.enum";
import { ObjectId } from "bson";
export class UnitService {
constructor() {}
async forceGenerate(unit: String) {
const relation = new Relation(
{
type: TypeRelation.USE,
topUnit: new ObjectId("5adf231d85dded040f3f6d03"),
lowerUnit: new ObjectId("5adf231d85dded040f3f6d03")
}
);
await relation.save();
}
}
然而,当我将new unitService()
放入forceCreateUnit()
时,效果很好。那是为什么?
我称这样的方法:
const homeController: HomeController = new HomeController();
homeRoutes.get("/prueba", homeController.forceCreateUnit);
答案 0 :(得分:0)
因此,{p>TypeError:无法读取未定义的属性“unitService”
我在TypeScript中有这个类,当我调用
State
时,我收到错误。
ZipCode
为this.unitService
。问题来自您拨打this
的方式。
试试:
undefined