【问题标题】:Typescript syntax error when Consuming Google Map Geocoding API使用 Google Map Geocoding API 时出现打字稿语法错误
【发布时间】:2018-09-03 23:53:23
【问题描述】:

我正在使用 Ionic3,我正在使用 Google Map Geocoding Google Map Geocoding API,我在这一行中发现了一个语法错误:

result = data.results[1].formatted_address;
Error: Property results does not exist in type Object

我已经用一个肮脏的解决方案解决了这个问题,我想问有没有人给我们一个更好的解决方案。

我的解决方案是在同一个文件中的提供程序类之前创建一个接口,并从我已转换并分配给变量数据的订阅 data2 中获取。

providers/rest/rest.ts:

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);
      });
    });
  } 

}

【问题讨论】:

    标签: angular ionic-framework google-maps-api-3 geocoding typescript-typings


    【解决方案1】:

    我相信这只是编辑器向您显示的编译警告/错误。 您可以将 data2 声明为 any 类型,这不会导致 tsc 编译器出错。您也不必为此定义任何接口。执行以下操作:

    this.http.get(apiUrl).subscribe((data2: any) =&gt; {//your implementation}

    但是,我建议使用接口是一个好主意,因为它可以让您的测试知道当您调用该 api 时期望什么样的对象。理想情况下,如果我知道来自 api 的响应类型,我会像您一样定义一个接口,并拥有该接口类型的 data2,例如:

    interface IData {
      'results':[    
        {
          "address_components": Object[],
          "formatted_address" : string,
        }
      ]
    };
    

    this.http.get(apiUrl).subscribe((data2: IData) =&gt; {//your implementation}

    参考这个StackBlitz

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      相关资源
      最近更新 更多