Axteam Axteam - 1 month ago 9
Node.js Question

typescript + node How to get instanse from methods?

After server rebuild, compiller creates instanse in included api controller here:

NewController.ts



import express = require("express");
import INew = require("../interface/INew");
import NewRepository = require("../repositories/NewRepository");

class NewController {
private _newRepository: INew;
constructor() {
this._newRepository = new NewRepository();
this._newRepository.findById(5);
}

retrieve(req: express.Request, res: express.Response): void {
try {
console.log('-----------retrieve--------------------');
this._newRepository.findById(2);
}
catch (e) {
console.log(e);
}
}

}

Object.seal(NewController);
export = NewController;





constructor works: i see console message:


-------------NewRepository------------------
5 'RESULT'



NewRepository.ts:


import INew = require("../interface/INew");
import bluebird = require("bluebird");

class NewRepository implements INew {
sd: string;

constructor() {
console.log('-------------NewRepository------------------');
}

findById(id: number): void {
setTimeout(function () {
console.log(id, 'RESULT');
}, 3000);
}
}

export = NewRepository;





INew.ts


interface INew {
findById: (id: number) => void;
sd: string;
}

export = INew;





Buut when i use controller's method 'retrieve', visit rout '/new' then i get error [TypeError: Cannot read property '_newRepository' of undefined] instead : 2 'RESULT'

Angular 2 helps me with routing:



.............
getCarsRestful(): Promise<New[]> {
console.log('-------------------------------');
return this.http.get('api/new')
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
...................





and execute backend:
NewRoutes.ts



import express = require("express");
import NewController = require('../controllers/NewController');

var router = express.Router();

class NewRoutes {
private _newController: NewController;

constructor() {
this._newController = new NewController()
}

get routes() {
var controller = this._newController;
router.get("/new", controller.retrieve);
return router;
}

}


Object.seal(NewRoutes);
export = NewRoutes;





my created instanse '_newRepository' doesn't exist already, why? i get console log:


-----------retrieve--------------------
[TypeError: Cannot read property '_newRepository' of undefined]



Help please, how to make 'singltone' in ts
i don't want to create it in every controller's method, though, that works:



.................
retrieve(req: express.Request, res: express.Response): void {
try {
var _newRepository: INew;
_newRepository = new NewRepository();
_newRepository.findById(2);
.............




Answer

Try explicitly set this in router config:

 router.get("/new", controller.retrieve.bind(controller));
Comments