Reputation: 113
I use exercise in html like {{exercise.name}}
.
It dosen't have problem at first.
But as you can see below, I want to have exercise.time
value minus for every 1sec.
But I can't access exercise object in setInterval()
.
I logged it but only came out null.
How can I access it and give minus for every second?
(minused number should be displayed).
export class ExercisePage {
exercise:any;
constructor(public navCtrl: NavController, public navParams: NavParams) {
console.log(this.navParams.get("data"));
this.exercise=this.navParams.get("data");
console.log(this.exercise);
console.log("시간2 : "+this.exercise.time);
var time=this.exercise.time;
setInterval(function(){
time--;
console.log(this.exercise);
},5000)
console.log("22");
}
ionViewDidLoad() {
console.log('ionViewDidLoad ExercisePage');
}
}
HTML
<p>{{exercise.time}}</p>
I changed a bit adding reduce function but it won't work neither.
export class ExercisePage {
exercise:any;
constructor(public navCtrl: NavController, public navParams: NavParams) {
console.log(this.navParams.get("data"));
this.exercise=this.navParams.get("data");
console.log(this.exercise);
console.log("시간2 : "+this.exercise.time);
var time=this.exercise.time;
setInterval(function(){
time--;
this.reduce(time);
},5000)
console.log("22");
}
reduce(time){
console.log("reduce : "+time);
console.log(this.exercise.time);
this.exercise.time=time;
}
}
Upvotes: 1
Views: 87
Reputation: 141
If you do not want to use Arrow functions as sebaferreras proposed you can alternatively use this method:
// ...
var tthis = this; // var that = this if you prefer
setInterval(function() {
time--;
console.log(tthis.exercise); // It should also work! ;)
}, 5000)
// ...
I suggest you to use arrow functions as it is now standard (I think) in Javascript and Typescript :)
Upvotes: 1
Reputation: 44659
You should use Arrow functions. By using arrow functions, the this
property is not overwritten and still references the component instance (otherwise, the this
keyword points to the inner function, and your component's methods and variables are not defined in it):
// ...
setInterval(() => {
time--;
console.log(this.exercise); // Now it should work! :)
}, 5000)
// ...
Upvotes: 1