AntonKad AntonKad - 1 month ago 11
HTTP Question

How to where do i process my data with observable .map and .subscribe

I'm retriving some data from my API:

[
{
"id": 1,
"lat": 50.607084,
"lng": 3.043099
},
{
"id": 2,
"lat": 50.607084,
"lng": 3.043099
},
]


I'd like to process the data only with reactive programing so that inside my request, google map markers get created.

this.http.get('http://api/getData')
.map(res => {
return res.json()
})
.subscribe(
data => {
console.log(data);
});


when doing this i'm getting a lot of objects, i could not fin a way to log or isolate only the latitude (i get "unknown").

I'd like to be able to put a function inside the ".map" (observable ?) that will get all variable,
and create markersOptions that i'll put in an array.

let markerOptions: GoogleMapsMarkerOptions = {
position: latlng,
title: 'id'
};


From wath i've seen on google, most of people prefer put the object in a private variable and i assume take care of it, in an other function.

Answer

What you need to do is mapping the array retrieved from the server to a list of GoogleMapsMarkerOptions. So, (I don't know the constructor of GoogleMapsMarkerOptions) something like:

this.http.get('http://api/getData')
    .map(res => {
      return res.json().map(x => {
         return new GoogleMapsMarkerOptions({
             title: x.it,
             position: new GoogleMapsLatLng(x.lat, x.lng)
         });
      });

    })
    .subscribe(
      data => {
        console.log(data);
});

The second map is a standard javascript method (not rxjs). If you need to support old browsers you can use lodash or underscore.