1

I am pushing the google coordinates into array but if I print console.log(this.markersData) the result is an empty array with objects-->[]

After second click I am getting an array with an object like this [object]

enter image description here

I will need the data of the first array as well. What I am doing wrong?

HTML

<button (click)="addPlace()" > </button>

Angular2 Function

import {Component, Input,OnInit, Output, EventEmitter,ElementRef} from '@angular/core';
import { Http, Headers, RequestOptions } from "@angular/http";
import {Observable} from 'rxjs/Rx';   

export class GoogleMapComponent  {

    markersData:any[] = [];

    addPlace(){
       this.http.get('https://maps.googleapis.com/maps/api/geocode/json?address=Rom').map((res: any) => res.json())
          .subscribe((res: any) => {
             // console.log(res.results[0].geometry.location);
             var geo = res.results[0].geometry.location;
                if(geo != undefined){
                   this.markersData.push(geo);  
                }
           }, 
           (error: any) => {
              console.log(error);
           });
       }
        console.log(this.markersData)
    }

1 Answer 1

1

After formatting your code, it looks like that your console.log is outstide your observable subscription (actually, it's a bit lost in nowhere...), therefore, it appears before the request is completed. This would explain why the second time it works.

Just tested with this plunker: http://plnkr.co/edit/qktCQKt9LLrzqogdkRho and it seems OK to me.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok thanx this was the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.