Reputation: 1279
I created a sample app in nodeJs that uses pg-promise to execute a query in Postgres. And wrapped it with a class called PostgresDataAccess. On the code below, why can't I access the "dal" object from my get and getOne function. The "this" keyword returns undefined. Can someone please explain this?
import { Router, Request, Response, NextFunction } from 'express';
import { PostgresDataAccess } from '../dal/postgres';
const config = require('../../config/config');
export class ProjectRouter {
public router: Router;
dal: PostgresDataAccess;
/**
* Construct the Project Router.
*/
constructor() {
this.dal = new PostgresDataAccess(config);
this.router = Router();
this.init();
}
/**
* Take each handler, and attach to one of the Express.Router's endpoints.
*/
init() {
this.router.get('/', this.get);
this.router.get('/:id', this.getOne);
}
/**
* GET: Returns all projects.
*/
get(req: Request, res: Response, next: NextFunction) {
let projects = this.dal.queryDb('select * from projects', null, res);
}
/**
* GET: Retuns one project by id.
*/
getOne(req: Request, res: Response, next: NextFunction) {
let projects = this.dal.queryDb('select * from projects where id = $1', [req.params.id], res);
}
}
const projectRouter = new ProjectRouter();
export default projectRouter.router;
Upvotes: 0
Views: 139
Reputation: 276239
why can't I access the "dal" object from my get and getOne function. The "this" keyword returns undefined
Change :
get(req: Request, res: Response, next: NextFunction) {
let projects = this.dal.queryDb('select * from projects', null, res);
}
to
get = (req: Request, res: Response, next: NextFunction) => {
let projects = this.dal.queryDb('select * from projects', null, res);
}
As arrow functions preserve this
Same for getOne
.
Upvotes: 2