Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push an object to array in angular2 and typescript?

i have defined an array as follows,

markers: marker[] = [
    {
      lat: 51.673858,
      lng: 7.815982,
      label: 'A',
      draggable: true
    }
  ];

i am getting data from rest service and push the new object to markers.

private data: any;
  findLocation(): void {
    let result;
    result =   this.geoService.loaddata(this.location)
     .subscribe(data => {
       result = data;
       console.log(result);
       this.markers.push({'lat':results[0].geometry.location.lat,'lng':results[0].geometry.location.lng})
     });
  }

it throws an error saying file:

message: 'Argument of type '{ 'lat': any; }' is not assignable to parameter of type 'marker'. Property 'lng' is missing in type '{ 'lat': any; }'.'

result is

{ "results" : [ { "address_components" : [ { "long_name" : "Colombo", "short_name" : "Colombo", "types" : [ "locality", "political" ] }, { "long_name" : "Colombo", "short_name" : "Colombo", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "Western Province", "short_name" : "WP", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "Sri Lanka", "short_name" : "LK", "types" : [ "country", "political" ] } ], "formatted_address" : "Colombo, Sri Lanka", "geometry" : { "bounds" : { "northeast" : { "lat" : 6.9812866, "lng" : 79.8900852 }, "southwest" : { "lat" : 6.862390700000001, "lng" : 79.8223258 } }, "location" : { "lat" : 6.9270786, "lng" : 79.861243 }, "location_type" : "APPROXIMATE", "viewport" : { "northeast" : { "lat" : 6.980584400000001, "lng" : 79.8900852 }, "southwest" : { "lat" : 6.8625113, "lng" : 79.8225192 } } }, "place_id" : "ChIJA3B6D9FT4joRjYPTMk0uCzI", "types" : [ "locality", "political" ] } ], "status" : "OK" }

like image 414
Sajeetharan Avatar asked Dec 03 '25 12:12

Sajeetharan


1 Answers

You have subscribed your data to result, not results.

private data: any;
  findLocation(): void {
    let result;
    // no use for "result" below
    // result = this.geoService.loaddata(this.location)
    // use the following instead
    this.geoService.loaddata(this.location)
     .subscribe(data => {
       result = data;
       console.log(result);
       this.markers.push({'lat':results[0].geometry.location.lat,'lng':results[0].geometry.location.lng})
     });
  }

so your push should look like:

this.markers.push({'lat':result[0].geometry.location.lat,'lng':result[0].geometry.location.lng})
         });

But this too will throw an error because in markers you have also declared label and draggable, so you need to push values to those attributes too.

like image 118
AT82 Avatar answered Dec 05 '25 06:12

AT82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!