I get this error message..
ERROR TypeError: Cannot read properties of undefined (reading 'geoCoord')
at Object.next (customers.service.ts:16:38)
If I give the "lon" and the "lat" variables a fixed Value, like 51.1634 and 10.4477, the function works. So I guess the problem comes from the get request or the way i target the json data.. Can someone help me out?
The Error occurs in this line.. why cant i acces the values?
const lon = c.customerAdress.geoCoord.longitudeCoord;
const lat = c.customerAdress.geoCoord.latitudeCoord;
My Service looks like this
export class CustomersService {
customers: string = '../../assets/data/customerdata.json';
constructor(private http: HttpClient) {}
makeCustomerMarkers(map: L.Map): void {
this.http.get(this.customers).subscribe((res: any) => {
for (const c of res.customerArray) {
const lon = c.customerAdress.geoCoord.longitudeCoord;
const lat = c.customerAdress.geoCoord.latitudeCoord;
const marker = L.marker([lat, lon]);
marker.addTo(map);
}
});
}
}
This is the component where i call the service
ngAfterViewInit(): void {
this.initMap();
this.customersService.makeCustomerMarkers(this.map);
}
This is my data
{
"customerArray": [
{
"customerAddress": {
"country": "Deutschland",
"geoCoord": {
"longitudeCoord": 10.4477,
"latitudeCoord": 51.1634
}
},
"phone": "0145221551",
"eMail": "[email protected]",
"homepage": "www.google.de",
},
{
"customerAddress": {
"country": "Deutschland",
"geoCoord": {
"longitudeCoord": 10.4477,
"latitudeCoord": 51.1634
}
},
"phone": "0145221551",
"eMail": "[email protected]",
"homepage": "www.google.de",
},
{
"customerAddress": {
"country": "Deutschland",
"geoCoord": {
"longitudeCoord": 10.4477,
"latitudeCoord": 51.1634
}
},
"phone": "0145221551",
"eMail": "[email protected]",
"homepage": "www.google.de",
}
]
}
CodePudding user response:
use safe traversal operator ?
like below.
const lon = c?.customerAdress?.geoCoord?.longitudeCoord;
const lat = c?.customerAdress?.geoCoord?.latitudeCoord;