Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access constructor properties from a setInterval on angular2

It seems that i cant access the constructor properties from an setInterval and i need to get and to modify the properties . any help on how can i solve this ?

startit() {
    console.log(this.page,this.nrpages) //works
    setInterval(function() {
        console.log(this.currentPage,this.nrpages) // undefined undefined
like image 603
Rus Mine Avatar asked Feb 05 '26 12:02

Rus Mine


2 Answers

Use arrow function

startit() {
  console.log(this.page,this.nrpages) //works
  setInterval(() => {
      console.log(this.currentPage,this.nrpages);
  }); 
like image 50
Günter Zöchbauer Avatar answered Feb 07 '26 02:02

Günter Zöchbauer


The key point here is that this points to the current execution context. So inside setInterval function this is not referring to your outer execution context. You can do something like:

startit() {
    console.log(this.page,this.nrpages) //works
    var thiObj = this;
    setInterval(function() {
        console.log(thisObj.currentPage,thisObj.nrpages) //works
like image 20
Saurabh Maurya Avatar answered Feb 07 '26 01:02

Saurabh Maurya