Use variable this in another function


#1

I Have a problem with the variable this in angularjs2 and ionic 2

I have this fuction:

getAnuncio(id_anuncio){
console.log(id_anuncio)
var token=this.local.get('token')._result; 
var headers= new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'Token '+token);
datos="id_anuncio="+id_anuncio;
this.http.post('http://127.0.0.1:8000/envios/getAnuncioPorId/',datos , {
    headers: headers

})

.subscribe(success => {
    this.anuncio=success.json();
    console.log("BIENNN");
    console.log(success);
    console.log(this.anuncio);
    return this.anuncio;



}

}

I call it from another function:

cargarMapa(){

this.anuncio=this.getAnuncio(this.envio.anuncio);
console.log(this.anuncio);
//console.log(anuncio);
//this.getOferta(this.envio.oferta);
//console.log(this.oferta)
}

But when I try to log this.anuncio, it is undefined.

I need to store the data in a variable to use it from other function.

Anybody could help me?

Here is the code: https://github.com/p02diada/cyclaClientv2/blob/master/app/pages/sending-details/sending-details.js


#2

getAnuncio() doesn’t return anything. You would have caught this at compile time if you were using TypeScript.


#3

Maybe this helps:

let self: any = this;

...

.subscribe(success => {
    self.anuncio=success.json();

#4

could you explain me this a bit more?


#5

I recommend you read about js promises. Observer is similar.


#6

thank you very much. I have fixed it with this answer:

http://stackoverflow.com/questions/37281573/use-variable-this-in-another-function