【发布时间】:2020-10-25 10:51:43
【问题描述】:
这是快速打字稿代码。我正在尝试使用服务从数据库中获取数据,但出现此错误:Cannot read property 'populationService' of undefined。
Controller.ts =>
import { PopulationService } from "../services/population.service";
export class PopulationController implements IController {
public path: string = "/population";
public router = Router();
private populationService: PopulationService = new PopulationService();
constructor() {
this.initializeRoutes();
}
private initializeRoutes() {
this.router.get(`${this.path}/getEmployer`, this.getEmployer);
}
private async getEmployer(request: Request, response: Response, next: NextFunction) {
try {
let result = await this.populationService.getEmployerFromService();
return response.status(200).send(result);
}
catch (error) {
next(error);
}
}
}
Service.ts =>
import { pool } from "../../config/database";
export class PopulationService {
public async getEmployerFromService(): Promise<any> {
let sql = `SELECT * FROM population;`;
let result = await pool.query(sql);
return result.rows;
}
}
这有什么问题?我使用 new 关键字在控制器中使用服务,但仍然出现此错误。
【问题讨论】:
标签: typescript api express backend