Typescript 如何在控制器中使用服务?-快速打字脚本
这是ExpressTypeScript代码。我试图使用服务从数据库中获取数据,但遇到以下错误:Typescript 如何在控制器中使用服务?-快速打字脚本,typescript,api,express,backend,Typescript,Api,Express,Backend,这是ExpressTypeScript代码。我试图使用服务从数据库中获取数据,但遇到以下错误:无法读取未定义的属性“populationService” Controller.ts=> import { PopulationService } from "../services/population.service"; export class PopulationController implements IController { public path: string
无法读取未定义的属性“populationService”
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);
}
}
}
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;
}
}
Service.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);
}
}
}
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;
}
}
从“../../config/database”导入{pool}”;
导出类填充服务{
公共异步getEmployerFromService():承诺{
让sql=`SELECT*FROM population;`;
让result=wait pool.query(sql);
返回result.rows;
}
}
这有什么问题?我使用new关键字在controller中使用service,但仍然出现此错误。因为您将
this.getEmployer
作为一个直接向上的函数传递,所以对this
的引用丢失。有很多方法可以解决这个问题,但我喜欢这种方法(在类构造函数中):
constructor(){
this.getEmployer=this.getEmployer.bind(this);
this.initializeRoutes();
}
我们还有另一个选择,那就是我们可以使用make-it-as-arrow函数
private getEmployer = async (request: Request, response: Response, next: NextFunction) => {
let result = await this.populationService.getEmployerFromService();
return response.status(200).send(result);
}
但我不知道这是否是一个完美的解决方案。如果您有更好的解决方案,请在此处添加。否@Evert,此操作不起作用,仍然会出现相同的错误,请给出任何其他建议