我正在home.ts
中使用谷歌地图方法中的IONIC home.ts
中的API调用中收到的数据。但它最终会出现空值或未定义的错误。
如何使用另一种方法中的数据?
这是我的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格式的这种情况如何处理问题??
答案 0 :(得分:1)
您需要像这样更改代码:
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
})
}