我试图从HTTP响应 -
中提取生成的JSON中的lat和lng值 lat: any;
lng: any;
geoResult: any;
public getGeoCoordinates(store) {
let apiUrl = '/assets/GoogleGeoCoordinates.json';
this.http.get(apiUrl).subscribe( resp => {
this.geoResult = resp;
});
}
从上面的方法,我试图捕获如下的值
if (resp['status'] == 'OK' && resp['results']['length'] > 0) {
this.lat = resp['results'][0]['geometry']['location']['lat'];
this.lng = resp['results'][0]['geometry']['location']['lng'];
}
如果我使用alert(),例如提醒('纬度:' + resp ['结果'] [0] ['几何'] [& #39;位置'] [' LAT']);
警告显示该值。
如果我将该值存储在' this.lat'变量,我得到了#undefined'
有人可以帮助我,了解从json HTTP响应中获取值
JSON文件内容 - GoogleGeoCoordinates.json
{
"results": [
{
"address_components": [
{
"long_name": "120",
"short_name": "120",
"types": [
"street_number"
]
},
{
"long_name": "West 56th Street",
"short_name": "W 56th St",
"types": [
"route"
]
},
{
"long_name": "Manhattan",
"short_name": "Manhattan",
"types": [
"political",
"sublocality",
"sublocality_level_1"
]
},
{
"long_name": "New York",
"short_name": "New York",
"types": [
"locality",
"political"
]
},
{
"long_name": "New York County",
"short_name": "New York County",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "New York",
"short_name": "NY",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "United States",
"short_name": "US",
"types": [
"country",
"political"
]
},
{
"long_name": "10019",
"short_name": "10019",
"types": [
"postal_code"
]
}
],
"formatted_address": "120 W 56th St, New York, NY 10019, USA",
"geometry": {
"location": {
"lat": 40.7640254,
"lng": -73.97896
},
"location_type": "ROOFTOP",
"viewport": {
"northeast": {
"lat": 40.7653743802915,
"lng": -73.97761101970849
},
"southwest": {
"lat": 40.7626764197085,
"lng": -73.98030898029151
}
}
},
"place_id": "ChIJE4YK3PlYwokRybTACneYny4",
"types": [
"street_address"
]
}
],
"status": "OK"
}
答案 0 :(得分:0)
我已经在'subscribe'之外分配了值,它似乎已经开始工作了。
工作代码如下 -
public getGeoCoordinates(store) {
let apiUrl = '/assets/GoogleGeoCoordinates.json';
this.http.get(apiUrl).subscribe( resp => {
this.geoResult = resp;
});
this.lat = this.geoResult['results'][0]['geometry']['location']['lat'];
this.lng = this.geoResult['results'][0]['geometry']['location']['lng'];
}