Unable to access objects in Typescript -
i unable access objects declared within class in typescript functions. here's have:
export class questions { credentials:mysqlcredentials.mysqlcredentials; sqlconnector:mysql.mysql; constructor() { this.credentials = new mysqlcredentials.mysqlcredentials('192.168.249.139', 'dev', 'dev', 'test'); this.sqlconnector = new mysql.mysql(this.credentials); } addquestion(req, res) { var q = ...<lot of code on here> ; this.sqlconnector.query(q, null); //error shown line res.send(); } } error: typeerror: cannot call method 'query' of undefined
if code structured shown above i.e. sqlconnector variable defined in typescript class, throws error. if place sqlconnector outside typescript class works fine. need fix need sqlconnector object inside class.
export class questions { credentials:mysqlcredentials.mysqlcredentials; constructor() { this.credentials = new mysqlcredentials.mysqlcredentials('192.168.249.139', 'dev', 'dev', 'test'); sqlconnector = new mysql.mysql(this.credentials); } addquestion(req, res) { var q = ...<lot of code on here> ; sqlconnector.query(q, null); //error shown line res.send(); } } var sqlconnector;
are calling class in new context (for example using event handler)?
if so, this
becomes context of event, not class context. common javascript problem can happen in typescript too.
you can solve scope issue in number of ways:
using arrow function
if use arrow function assign function member on questions class, use class scope.
export class questions { credentials:mysqlcredentials.mysqlcredentials; sqlconnector:mysql.mysql; constructor() { this.credentials = new mysqlcredentials.mysqlcredentials('192.168.249.139', 'dev', 'dev', 'test'); this.sqlconnector = new mysql.mysql(this.credentials); } addquestion = (req, res) => { var q = ...<lot of code on here> ; this.sqlconnector.query(q, null); //error shown line res.send(); } }
using call
set scope context
this alternative solution means questions class doesn't need concerned scope - if call method different scope context, use call
assign question instance scope.
element.onclick = function () { questions.addquestion.call(questions, arga, argb); };
Comments
Post a Comment