2

I was trying to create an autocomplete input field with angular 4. I'm new to the angular framework and Typescript. From requirements, I should implement by using angular 4(Typescript). But the response of the API is not good when working with angular 4. Actually, I wanted to create 'place autosuggestion' thing. But got the following response...

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

If you are familiar with this kind of issues, Please suggest me the right way to solve this issue. Thanks in advance.

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


}
Mike Feltman
  • 5,160
  • 1
  • 17
  • 38
Renjith V R
  • 2,981
  • 2
  • 22
  • 32

1 Answers1

0

You need to .subscribe to the observable returned by http.get().

You can either do

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

or

  • 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());

That of course requires you to define this.result in your component. If you want to return the observable, just let the method return as you have, and .subscribe() to it from where it's called.

Update: Not really related to the technical issue of this question, but nontheless related and perhaps required to get it working. The correct way to use the Google Places autocomplete is to use the Places library instead of AJAX requests. Have a look at this this SO answer.

Daniel B
  • 8,770
  • 5
  • 43
  • 76
  • Got some errors- > `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…}` – Renjith V R Jul 17 '17 at 13:35
  • That has to do with CORS and isn't really related to the first issue. – Daniel B Jul 17 '17 at 13:50
  • I will check that. Thank you. – Renjith V R Jul 17 '17 at 14:19