[英]use variable this in another function
我在angularjs2和ionic 2中的變量this
有問題
我有這個功能:
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;
}
}
我從另一個函數調用它:
cargarMapa(){
this.anuncio=this.getAnuncio(this.envio.anuncio);
console.log(this.anuncio);
//console.log(anuncio);
//this.getOferta(this.envio.oferta);
//console.log(this.oferta)
}
但是,當我嘗試登錄this.anuncio
,它是未定義的。
我需要將數據存儲在變量中以從其他函數使用它。
有人可以幫助我嗎?
這是代碼: https : //github.com/p02diada/cyclaClientv2/blob/master/app/pages/sending-details/sending-details.js
您可以通過以下方式利用do
運算符:
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
})
.map(res => success.json())
.do(data => {
this.anuncio = data;
});
}
這樣,您可以在getAnuncio
方法之外訂閱可觀察的getAnuncio
:
this.anuncio=this.getAnuncio(this.envio.anuncio).subscribe(
(anuncio) => {
// do something
console.log(anuncio);
}
);
不要忘記事情是異步的。
如果要實現一種緩存,請使用以下命令:
getAnuncio(id_anuncio){
if (this.anuncio) {
return Observable.of(this.anuncio);
} else {
var token=this.local.get('token')._result;
var headers= new Headers();
(...)
}
}
通過直接使用this.anuncio
,您無法確定數據是否存在...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.