angular - ¿Cómo agregar un objeto a un arreglo en angular2 y typescript?
He definido un arreglo de la siguiente manera,
markers: marker[] = [
{
lat: 51.673858,
lng: 7.815982,
label: 'A',
draggable: true
}
];
Estoy obteniendo datos de un servicio REST y empujando el nuevo objeto a los marcadores.
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})
});
}
lanza un error diciendo archivo:
message: 'Argument of type '{ 'lat': any; }' is not assignable to
parameter of type 'marker'. Property 'lng' is missing in type '{
'lat': any; }'.'resultado es
{ "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" }Respuesta #1
Has suscrito tus datos a result, no a 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})
});
}
así que tu push debería verse así:
this.markers.push({'lat':result[0].geometry.location.lat,'lng':result[0].geometry.location.lng})
});
Pero esto también generará un error porque en los marcadores también has declarado label y draggable, por lo que necesitas asignar valores a esos atributos también.
