2017-07-17 60 views
2

我正在嘗試創建一個角度爲4的自動填充輸入字段。我是新的角框架和Typescript。根據要求,我應該使用angular 4(Typescript)來實現。但是在使用角度4時API的反應並不好。實際上,我想創建'place autosuggestion'這個東西。但得到以下回應...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()); 
    } 


} 

回答

0

您需要.subscribe到可觀察到的由http.get()返回。

您可以做

  • 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,那麼就讓這個方法像你一樣返回,並且從它被調用的地方返回。

更新: 沒有真正涉及到這個問題的技術問題,但nonthless相關,也許需要得到它的工作。使用Google商家信息自動填充功能的正確方法是使用Places library而不是AJAX請求。看看這個this SO answer

+0

有一些錯誤 - > XMLHttpRequest無法加載https://maps.googleapis.com/maps/api/place/autocomplete/json?....沒有'Access-Control-Allow-Origin'頭部存在請求的資源。因此不允許訪問Origin'http:// localhost:4200'。 core.es5.js:1020錯誤響應{_body:ProgressEvent,status:0,ok:false,statusText:「」,headers:Headers ...}' –

+0

這與CORS有關,並且與第一個問題。 –

+0

我會檢查。謝謝。 –

相關問題