gg123
gg123

Reputation: 31

How to get values from Object in Angular?

I have a project where I get location data from API (opencagedata):


export class LocationComponent implements OnInit {

  longitude: number;
  latitude: number;
  location: Object;
  name: String;


  constructor(private _http: HttpService) { }

  ngOnInit(): void {

    navigator.geolocation.getCurrentPosition((position) =>{
      this.latitude = position.coords.latitude;
      this.longitude = position.coords.longitude;
      this._http.getLocation(this.latitude, this.longitude).subscribe(data => {
        this.location = data;
        console.log(this.location);
      })
    })
  }

}

And in console I can see my data displayed but I want to have the name of the city in variable name.

I have tried:

this.name = this.location.results[0].components.city

but it doesn't work because of an error that method results doesn't exists on type 'Object'. Any suggestions?

console.log(data) outputs:

location.component.ts:28 {documentation: "https://opencagedata.com/api", licenses: Array(1), rate: {…}, **results: Array(1)**, status: {…}, …}documentation: "https://opencagedata.com/api"licenses: [{…}]rate: limit: 2500remaining: 2496reset: 1583884800__proto__: Objectresults: [{…}]status: {code: 200, message: "OK"}stay_informed: {blog: "https://blog.opencagedata.com", twitter: "https://twitter.com/opencagedata"}thanks: "For using an OpenCage API"timestamp: {created_http: "Tue, 10 Mar 2020 16:08:09 GMT", created_unix: 1583856489}total_results: 1__proto__: Object
temp1
{documentation: "https://opencagedata.com/api", licenses: Array(1), rate: {…}, results: Array(1), status: {…}, …}

And the data I need are in the array results.

The method getLocation() that is in file http.service.ts

getLocation(longitude, latitude) {
    return this.http.get('https://api.opencagedata.com/geocode/v1/json?key=(i have my key here)&q='+longitude+"+"+latitude+'&pretty=1')
  }

Upvotes: 1

Views: 2862

Answers (1)

Emilien
Emilien

Reputation: 2761

According to what I've read in Open Cage Documentation, you don't have the good format.

Could you try with :

this._http.getLocation(this.latitude, this.longitude).subscribe(data => {
  this.location = data;
  this.name = data.results[0].components.city;
})

On their documentation, Reverse Geocoding return this JSON :

{ 
  // Others objects or properties
  "results" : [
    {
      // Others objects or properties
      "components" : {
        "ISO_3166-1_alpha-2" : "NA",
        "ISO_3166-1_alpha-3" : "NAM",
         "_category" : "commerce",
         "_type" : "restaurant",
         "city" : "Swakopmund", // <-- Here is what you want
         "continent" : "Africa",
         "country" : "Namibia",
         "country_code" : "na",
         "restaurant" : "Beryl's Restaurant",
         "road" : "Woermann St",
         "state" : "Erongo Region",
         "suburb" : "Central"
       },
     }
  ],
  "total_results" : 1
}

Upvotes: 1

Related Questions