Reputation: 943
I'm working with Ionic3 and I'm consuming the Google Map Geocoding Google Map Geocoding API and I found a syntax error in this line :
result = data.results[1].formatted_address;
Error: Property results does not exist in type Object
I've resolved this issue using a dirty solution and I'm asking is there someone to give us a better Solution.
My Solution is to create an interface before my provider class in the same file and getting from subscribe data2 which I have casted and assign to variable data.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
interface data {
'results':[
{
"address_components": Object[],
"formatted_address" : string,
}
]
};
@Injectable()
export class RestProvider {
apiUrl1 = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=';//36.731470384526965,10.210593179614534
apiUrl2 = '&key=AIzaSyBtYmf_L2ESZVcnkeIHRw_uD0VQIBbFYAM';
constructor(public http: HttpClient) {
console.log('Hello RestProvider Provider');
}
getCity(latLng) {
let apiUrl = this.apiUrl1+latLng.lat()+','+latLng.lng()+this.apiUrl2;
return new Promise(resolve => {
this.http.get(apiUrl).subscribe(data2 => {
let result ='';
let data: data;
data = <data>data2;
if(data && data.results[1])
result = data.results[1].formatted_address;
else
result = 'Undefinied city'
resolve(result);
}, err => {
console.log(err);
});
});
}
}
Upvotes: 0
Views: 412
Reputation: 368
I believe this is just a compilation warning/error being shown to you by your editor. You can declare data2 as of type any, which will not cause tsc compiler to cause errors. You will not have to define any interface for this either. Do as below:
this.http.get(apiUrl).subscribe((data2: any) => {//your implementation}
But, I suggest using the interface is a good idea as it will let your tests know what kind of object to expect when you call that api. Ideally if I knew the type of the response from api I would define an interface like you did and have the data2 of the type of that interface like:
interface IData {
'results':[
{
"address_components": Object[],
"formatted_address" : string,
}
]
};
this.http.get(apiUrl).subscribe((data2: IData) => {//your implementation}
Refer to this StackBlitz
Upvotes: 2