【发布时间】:2020-03-11 00:38:09
【问题描述】:
我有一个项目,我从 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: {…}, …}
而我需要的数据在数组结果中。
文件http.service.ts中的getLocation()方法
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')
}
【问题讨论】:
-
“它不起作用”不是有效的问题陈述。你试过troubleshooting the problem?
-
你把
this.name = this.location.results.city放在哪里了? -
this.location或data的数据结构是什么? -
我已经把它放在console.log(this.location)下面了
-
"data" 是来自地理定位 API 的对象
标签: angular typescript