Help with call a function inside setInterval()


#1

Hello, I am developing a app with ionic 2 but I have a problem. I don’t know how to call a function inside setInterval() because the app does not recognise the constructor when I try it. I have this:

actualizarPosicion(){
 this.getTokenID();  
 var timer= setInterval(this.obtenerPosicion,5000);
 var timer2= setInterval(this.enviarPosicion,5000);
 //this.enviarPosicion();
}

enviarPosicion(){
  if (typeof this.latitude != 'undefined' && typeof this.longitude != 'undefined')
  {
    console.log(this.local);
    var token=this.token;
    var id_usuario=this.id_usuario;
    var headers= new Headers();
    console.log('latitud: '+this.latitude);
    datos="longitud_ciclista=4.7847038"+"&latitud_ciclista=37.8761787"+"&id_ciclista="+id_usuario;
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Authorization', 'Token e31e642fa2aa05743309a9a4deef815302c6c287');
    this.http.post('http://127.0.0.1:8000/usuarios/setPosicionCiclista/',datos,{
      headers:headers
    }).subscribe(success =>{
      console.log(success);
    }

  }
}

The problem is that the app does not recognise this.http.post, but when I try to call enviarPosicion outside of setInterval() It runs correctly.

Here is de complete code: https://github.com/p02diada/cyclaClientv2/blob/master/app/pages/login/login.js

Anyone knows how to fit it?


#2

You are being bitten by the fact that ‘this’ in JavaScript/TypeScript is weird.


#3

Thank you very much, I didn’t know it. It runs now.


#4

This link might help solve the issue with using setTimeout and setInterval methods in Ionic 2 applications:

setTimeout and setInterval methods: Ionic 2