![](/img/trans.png)
[英]python 3. Use variable from one method in another method within the same class
[英]How to use value of one method in another inside same class in Ionic?
我試圖使用從我的API調用收到離子數據home.ts
在谷歌地圖法home.ts
。但它最終給人一種空或未定義的錯誤。
如何在另一種方法中使用來自一種方法的數據?
這是我的home.ts
代碼
getResturentDetails(id){
const data = localStorage.getItem('userToken');
this.userPostData.api_token= data;
this.userPostData.resturentId= id;
this.authService.postData(this.userPostData,'resturentDetail').then((result)=>{
this.responseData = result;
console.log(this.responseData); //I can see data as expected
})
}
控制台日志的輸出是這樣的
{"id":"1","lat":"10.90" ,"lon":"89.00"}
JSON 對象表示法中的類似內容
我的構造函數
constructor(public nav: NavController,
public navParams:NavParams,
public tripService: TripService,
public authService:AuthServiceProvider
) {
// set sample data
this.getResturentDetails(this.navParams.get('id'));
console.log(this.responseData.lat); //saying undefined index lat
console.log(this.responseData.lon); //saying undefined index lon
this.DisplayMap(this.responseData.lat,this.responseData.lon);
}
ionViewDidLoad() {
}
那么我該如何處理這個問題?? 如果我的 API 返回一個數據數組,在這種情況下如何處理問題例如,如果 API 響應是這樣的
[{"id":"1","lat":"10.90" ,"lon":"89.00"},{"id":"2","lat":"10.90" ,"lon":"89.00"}]
像這樣的 JSON 格式,在這種情況下如何處理這個問題??
您需要像這樣更改代碼:
constructor(...) {
...
this.getResturentDetails(this.navParams.get('id')).then(result => {
this.responseData = result;
console.log(this.responseData.lat); // will not say undefined index lat
console.log(this.responseData.lon); //will not say undefined index lon
this.DisplayMap(this.responseData.lat,this.responseData.lon);
})
}
getResturentDetails(id){
const data = localStorage.getItem('userToken');
this.userPostData.api_token= data;
this.userPostData.resturentId= id;
return this.authService.postData(this.userPostData,'resturentDetail');
}
它不工作的原因是,異步行為:
只需按照下面代碼中的執行順序No,您將了解流程將如何實時執行
// this will call getResturentDetails , and consider it may take few sec
this.getResturentDetails(this.navParams.get('id')); // Execution sequence : 1
// next line will be executed before result returns coz of async behaviour
console.log(this.responseData.lat); // Execution sequence : 6
console.log(this.responseData.lon); // Execution sequence : 7
this.DisplayMap(this.responseData.lat,this.responseData.lon); // Execution sequence : 8
getResturentDetails(id){
const data = localStorage.getItem('userToken'); // Execution sequence : 2
this.userPostData.api_token= data; // Execution sequence : 3
this.userPostData.resturentId= id; // Execution sequence : 4
// Execution sequence : 5
this.authService.postData(this.userPostData,'resturentDetail').then((result)=>{
this.responseData = result; // Execution sequence : 9
console.log(this.responseData); // Execution sequence : 10
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.