【问题标题】:How to use service in controller? - Express Typescript如何在控制器中使用服务? - 快递打字稿
【发布时间】: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


    【解决方案1】:

    因为您将this.getEmployer 作为直接向上的函数传递,所以对this 的引用会丢失。有很多方法可以解决这个问题,但我喜欢这种方式(在你的类构造函数中):

    constructor() {
      this.getEmployer = this.getEmployer.bind(this);
      this.initializeRoutes();
    }
    

    【讨论】:

    • No @Evert,这不起作用,仍然遇到同样的错误,请提供任何其他建议
    【解决方案2】:

    我们还有另一种选择,那就是我们可以使用 make 它作为箭头函数。

    private getEmployer = async (request: Request, response: Response, next: NextFunction) => {
            let result = await this.populationService.getEmployerFromService();
            return response.status(200).send(result);
     }
    

    但我不知道这是否是完美的解决方案。如果您有更好的解决方案,请在此处添加。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-28
      • 2019-11-19
      • 2017-02-22
      • 2015-08-21
      • 2015-03-21
      • 2019-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多