Tony
Tony

Reputation: 243

Angular2 pushed array first index undefined

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

Upvotes: 1

Views: 595

Answers (1)

ssougnez
ssougnez

Reputation: 5886

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.

Upvotes: 1

Related Questions