【问题标题】:Angular 4 : Google Places autocomplete API is not workingAngular 4:Google Places 自动完成 API 不起作用
【发布时间】:2017-12-22 00:55:48
【问题描述】:

我试图用 angular 4 创建一个自动完成输入字段。我是 angular 框架和 Typescript 的新手。根据要求,我应该使用 angular 4(Typescript) 来实现。但是在使用 angular 4 时 API 的响应并不好。实际上,我想创建“放置自动建议”的东西。但是得到了以下响应...

Observable {_isScalar: false, source: Observable, operator: MapOperator}

如果您熟悉此类问题,请建议我解决此问题的正确方法。提前致谢。

google.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

import 'rxjs/Rx';

@Injectable()
export class GooglePlaces {

  constructor(private http: Http) {}

  getPlaces(place) {
          const key = "xxxxxxxxxxxx-axxxxxx-xxxxaxx";
          return this.http.get("https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+place+"&components=country:in&key="+key).map(res => res.json());
  }


}

【问题讨论】:

    标签: javascript angular google-maps autocomplete


    【解决方案1】:

    你需要 .subscribehttp.get() 返回的 observable。

    你可以这样做

    • this.http.get("https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+place+"&components=country:in&key="+key).map(res => res.json()).subscribe(result => this.result = result);

    • this.http.get("https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+place+"&components=country:in&key="+key).subscribe(result => this.result = result.json());

    这当然需要您在组件中定义this.result。如果您想返回 observable,只需让方法按原样返回,并从调用它的位置返回 .subscribe()

    更新: 与这个问题的技术问题并不真正相关,但仍然相关并且可能需要让它工作。使用 Google Places 自动完成功能的正确方法是使用 Places library 而不是 AJAX 请求。看看这个this SO answer

    【讨论】:

    • 有一些错误-> XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/place/autocomplete/json?.... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. core.es5.js:1020 ERROR Response {_body: ProgressEvent, status: 0, ok: false, statusText: "", headers: Headers…}
    • 这与CORS有关,与第一个问题无关。
    • 我会检查的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 2013-10-10
    • 1970-01-01
    • 2015-06-05
    • 2017-10-02
    • 1970-01-01
    相关资源
    最近更新 更多