0

i am new in Angular 2,i am trying to show marker on google map with array [{id:"1",lat:"",long:""},{id:"2",lat:"",long:""}], inside of socket i am able to get the data in this.markers but outside of function i mean on html the data is not showing, the markers variable is out of scope and its showing undefined if i print it outside

code --

import { Component, OnInit, ElementRef, OnDestroy } from '@angular/core';
import { ProjectService } from '../service/project.service';
import { AuthenticationService } from '../service/authenticate.service';
import { ChatService } from './chat.service';
import { AgmCoreModule } from 'angular2-google-maps/core';
import * as io from 'socket.io-client';
@Component({
    selector: 'car',
    templateUrl: 'car.component.html',
    styles: [` .sebm-google-map-container {
       height: 300px;
     }`]
})
export class carDetails implements OnInit {
    public markers: any[];
    private url = 'http://localhost:2222';
    private socket;
    connection;
    title: string = 'Map';
    lat: number = 22.57305679;
    lng: number = 88.43082201;
    public cabData: any = [];
    constructor(
        private AuthenticationService: AuthenticationService,
        private _elementRef: ElementRef
    ) { }

    ngOnInit() {
        this.socket = io(this.url);
        this.socket.emit("carArrayPosition", this.cabData);
        this.socket.on('currentCarPositionData', (data) => {
            this.markers = data;
           console.log(this.markers); //printing the data
        }); console.log(this.markers); //not printing data
    }



    logout() {
        this.AuthenticationService.logout();
    }

}
eko
  • 39,722
  • 10
  • 72
  • 98
Nilasis Sen
  • 299
  • 1
  • 10
  • i have put a data receiving interval of 9 sec to resolve this kind of problem . – Nilasis Sen Jul 31 '17 at 09:28
  • Don't put a 9s interval as a workaround. Understand what asynchronism is and how it works. You will get your markers data _when it's ready_, which means inside the callback function. Outside, it's undefined. – Jeremy Thille Jul 31 '17 at 09:38
  • i solved it, was kind of silly mistake as i did't notice the incoming data. it was not asynchronous issue because in case of map asynchronous dsnt mttr, marker can be loaded anytime . my db data type was string and on map we need float that was the issue .. – Nilasis Sen Jul 31 '17 at 12:22

0 Answers0