0

In the code console.log(this.gameIndex) prints out undefined. Why is this? When I console.log(this.gameIndex) within the constructor the correct value is printed out.

Typescript

export class HomeComponent implements OnInit {
  game:String;
  gameIndex;
  games:String[];
  constructor() { 
    this.gameIndex = 0;

    this.games = ['game1','game2','game3'];
    this.game = this.games[this.gameIndex];

    setInterval(this.rotatingBackground,3000);
    console.log(this.gameIndex);
  }

  ngOnInit() {


  }

  rotatingBackground():any {
    console.log(this.gameIndex);
    this.game = this.games[this.gameIndex];
    console.log(this.game);
  }


}
1
  • You should consider changing your properties types from String to string and from Number to number, because "in JavaScript the literals are considered better" (as mentioned here stackoverflow.com/a/14727461) Jul 5, 2019 at 5:47

2 Answers 2

0

Try to use like this,

        setInterval(() => this.rotatingBackground(), 1000);
1
0

It's because you haven't defined it.

gameIndex;

should be

gameIndex:Number;`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.