Извлечение данных из ответа HTTP - Angular 5 - PullRequest
0 голосов
/ 25 апреля 2018

Я пытаюсь извлечь значения lat и lng из полученного JSON из ответа HTTP -

  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 (), например, alert ('Latitude:' + resp ['results'] [0] ['geometry'] ['location'] ['lat']);

предупреждение показывает значение.

Если я сохраню это значение в переменной this.lat, я получу значение undefined

Может ли кто-нибудь мне помочь, чтобы понять, как получить значения из HTTP-ответа JSON

Содержимое файла 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"
}

1 Ответ

0 голосов
/ 25 апреля 2018

Я присвоил значения за пределами «подписки», и, похоже, начал работать.

рабочий код следующим образом -

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'];
  }
...