Reputation: 1348
I am new to Angular, and I have been trying to figure this out for hours. I can't get the lat and lng variables to return the number properly when I get them from JSON.
I am getting JSON from here: https://jsonplaceholder.typicode.com/users
Here is the component.html...
<div *ngIf="user$">
<ul>
<li><strong>Lat:</strong> {{ lat }}</li>
<li><strong>Lng:</strong> {{ lng }}</li>
</ul>
<agm-map [latitude]="lat" [longitude]="lng">
<agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>
</div>
It works as it should in the list and map elements when I set the values in the variables this way.
Working component.ts
export class DetailsComponent implements OnInit {
user$: any;
constructor(private data: DataService, private route: ActivatedRoute) {
this.route.params.subscribe( params => this.user$ = params.id)
}
ngOnInit() :void {
this.data.getUser(this.user$).subscribe(
data => {
this.user$ = data
console.log(this.lat, this.lng);
}
)
}
lat: number = -37.3159;
lng: number = 81.1496;
}
But as soon as I try to get values from JSON the variables return as the string, and the map and the marker don't work but the list element does.
Not working component.ts
export class DetailsComponent implements OnInit {
user$: any;
lat: number;
lng: number;
constructor(private data: DataService, private route: ActivatedRoute) {
this.route.params.subscribe( params => this.user$ = params.id)
}
ngOnInit() :void{
this.data.getUser(this.user$).subscribe(
data => {
this.user$ = data
this.lat = this.user$.address.geo.lat;
this.lng = this.user$.address.geo.lng;
console.log(this.lat, this.lng);
}
)
}
}
When I hover over the lat and lng variables in the Visual Studio Code either way, it looks identical and it says (property) DetailsComponent.lng : number or (property) DetailsComponent.lng : number.
Upvotes: 1
Views: 868
Reputation: 11000
Because agm
expects an integer value and you provide a string. I think the best way to convert it into number value (in case if your number format uses dot .
(not comma ,
), use a +
sign:
this.lat = +this.user$.address.geo.lat;
this.lng = +this.user$.address.geo.lng;
Upvotes: 3