Rus Mine
Rus Mine

Reputation: 1593

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

Upvotes: 2

Views: 1569

Answers (2)

Saurabh Maurya
Saurabh Maurya

Reputation: 1628

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

Upvotes: 4

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657937

Use arrow function

startit() {
  console.log(this.page,this.nrpages) //works
  setInterval(() => {
      console.log(this.currentPage,this.nrpages);
  }); 

Upvotes: 10

Related Questions