This specific piece of TypeScript code is causing me some trouble. I'm attempting to utilize a service to retrieve data from a database, but unfortunately, I keep encountering the following error message:
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;
}
}
What could possibly be the issue here? Despite using the new keyword to instantiate the service in the controller, I am still facing this persistent error.