TypeError:无法读取未定义的属性“unitService”

时间:2018-04-24 20:13:56

标签: javascript node.js typescript

我在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);

1 个答案:

答案 0 :(得分:0)

  

TypeError:无法读取未定义的属性“unitService”

     

我在TypeScript中有这个类,当我调用State时,我收到错误。

因此,{p> ZipCodethis.unitService。问题来自您拨打this的方式。

试试:

undefined