У меня есть проект, в котором я получаю данные о местоположении из 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);
})
})
}
}
И в консоли я вижу свои данные, но я хочу, чтобы название города отображалось в имени переменной.
Я пытался:
this.name = this.location.results[0].components.city
, но он не работает из-за ошибки, что результат метода не существует для типа «Объект». Любые предложения?
console.log (data) выводит:
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: {…}, …}
И мне нужны данные в массиве результатов.
Метод getLocation (), который в файле 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')
}