Dealing with Angular can be frustrating at times, especially when you encounter errors like "TypeError: Cannot

Encountering an Error Message...

ERROR TypeError: Cannot read properties of undefined (reading 'geoCoord')
at Object.next (customers.service.ts:16:38)

When assigning fixed values to "lon" and "lat" variables, like 51.1634 and 10.4477, the function works. There seems to be an issue with the get request or how I am accessing the JSON data. Any assistance would be appreciated.

The error is pinpointed to this line; why can't I access the values?

const lon = c.customerAdress.geoCoord.longitudeCoord;
const lat = c.customerAdress.geoCoord.latitudeCoord;

This is what my Service entails

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 where the service is invoked in a component

ngAfterViewInit(): void {
    this.initMap();
    this.customersService.makeCustomerMarkers(this.map);
  }

Below is the data structure being used

{
  "customerArray": [
    {
      "customerAddress": {
        "country": "Deutschland",
        "geoCoord": {
          "longitudeCoord": 10.4477,
          "latitudeCoord": 51.1634
        }
      },
      "phone": "0145221551",
      "eMail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7b3a2b4b387b3b5a6b4afaaa6aeabe9a3a2">[email protected]</a>",
      "homepage": "www.google.de",
    },
    {
      "customerAddress": {
        "country": "Deutschland",
        "geoCoord": {
          "longitudeCoord": 10.4477,
          "latitudeCoord": 51.1634
        }
      },
      "phone": "0145221551",
      "eMail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aedacbdddaeedadccfddc6c3cfc7c280cacb">[email protected]</a>",
      "homepage": "www.google.de",
    },
    {
      "customerAddress": {
        "country": "Deutschland",
        "geoCoord": {
          "longitudeCoord": 10.4477,
          "latitudeCoord": 51.1634
        }
      },
      "phone": "0145221551",
      "eMail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b0f1e080f3b0f091a0813161a1217551f1e">[email protected]</a>",
      "homepage": "www.google.de",
    }
  ]
}

Answer №1

To ensure safe traversal, incorporate the optional chaining operator ? as demonstrated in the following code snippet.

const long = c?.clientLocation?.geoCoordinates?.longitude;
const lati = c?.clientLocation?.geoCoordinates?.latitude;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`Creating the perfect bar``

Currently working on my resume using Angular and I am interested in incorporating a visual representation of my skill level in specific subjects. Came across something that caught my eye here: https://i.sstatic.net/84cir.png The challenge now is figuring ...

What is the best way to sort through an array using JavaScript?

Here's an array for you: values = ["10%", 1000, "5%", 2000] I'm looking to split this into two separate arrays like so: percentages = ["10%","5%"] numbers = [1000,2000] How can I achieve this using JavaSc ...

Guide to organizing the table according to the values (timestamps) in a specific column

In one of the tables I'm working with, there is a column called uploadedOn. You can see it in action here: https://stackblitz.com/edit/angular-ivy-tntvst?devToolsHeight=33&file=src/app/app.component.ts 1: https://i.stack.imgur.com/aQ6wh.png. My g ...

Issues persist with the LLIST *mylist[x]dataArray

After some experimentation... I declared int x; LLIST *mylist[x]; and then initialized x to 10 using bzero(mylist, sizeof(LLIST *)*x); However, this approach did not work as expected. Prior to that, I had the following code: int x=10; LLIST *mylist[x] ...

The Angular application has been successfully deployed on a Tomcat server as a war

I am planning to deploy a single page application (SPA) developed in Angular, along with various static files like *.css, .js, /assets/, all packed inside a war file on Tomcat. The issue I am facing is that whenever a user enters a path that does not corr ...

Testing Angular with Jasmine: The spy should have been called as expected

Seeking assistance for a persistent issue that has been troubling me. I am currently working on unit tests for a component I developed, and no matter what I try, I can't seem to resolve the recurring problem of an "Expected spy getTopRatedMedia to ha ...

React Project Encounters NPM Installation Failure

I recently started delving into the world of React and experimenting with different examples. Everything was running smoothly until I attempted to start the server [npm start] and encountered an error as shown below. Despite my best efforts, I can't p ...

What is the alternative to using toPromise() when utilizing await with an Observable?

This website mentions that "toPromise is now deprecated! (RxJS 5.5+)", however, I have been utilizing it recently with AngularFire2 (specifically when only one result is needed) in the following manner: const bar = await this.afs.doc(`documentPath`).value ...

Visualize complex JSON data within an Angular Material Table

The JSON file is structured as follows: { "products": { "items":[ { "productId": "1", "dept": "home", "itemtype": "small" }, { "productId": "2", "dept": "kitchen", "itemtype": "medium" ...

What is the reason behind Angular triggering @HostListener as soon as the element begins to appear in the DOM?

I encountered an issue while writing a directive to close an element when a user clicks outside of the host element. The problem seems to be that the @HostListener is triggered immediately once the element is displayed in the DOM. It might not actually be ...

Troubleshooting problems with primeng using angular-cli and webpack

In a starter project using Angular 2, angular-cli@webpack, and PrimeNG, I am encountering errors. The only UI component from PrimeNG in use is a dropdown that renders properly with its values, but the CSS theme is not being applied (see error messages belo ...

Using Promise to manipulate objects and arrays returned from functions

https://i.stack.imgur.com/jvFzC.png router.get('/', function (req, res, next) { var size = req.params.size ? parseInt(req.params.size) : 20; var page = req.params.page ? req.params.page>0 ? (size&(parseInt(req.params.page)-1)) : ...

Chart.js Axis Labels Orientation Guidelines

I am currently utilizing chart.js within an Angular 8 environment using Primeng. I am looking to customize the options for my chart as follows: For the y-axis ticks, set textDirection to 'ltr' For the x-axis ticks, set textDirection to 'rtl ...

Dealing with inconsistent wait problems in Angular applications with Protractor and Jasmine

In my current project, I am using Angular for building the application along with Protractor and Jasmine for e2e tests. However, we have been experiencing inconsistent test script failures during execution. To tackle this issue, we tried setting ignore.s ...

Capture stunning photos with Ionic Capacitor CameraPreview, where the camera is always front and center. Say goodbye to any

I'm currently working on developing a customized camera feature for a tablet application. One of the challenges I'm facing is getting buttons to float over the camera preview. Despite setting the isBack attribute to true, the camera preview remai ...

"Exploring the relationship between Typescript and Angular: transforming variables within different

Ever since I made the switch from JavaScript to TypeScript (Version 2.1.5), I have been facing an issue with the code that filters date selection. Despite my efforts, I haven't been able to find a good fix for it yet. Here are the two date-pickers: F ...

How can I use JavaScript to sort through an array and organize the data into groups?

Below is an array that I currently have: Status=["active","inactive","pending","active","completed","cancelled","active","completed"] I am looking to achieve the following result: StatusInfo=["active":3,"inactive":2,"pending":1, "completed":2, "cancelle ...

Vue Error: The method "reduce" is not a function

Currently implementing Vue.js with Typescript and aiming to utilize reduce for summing up the values of desktopCnt and mobileCnt from the deviceCount array to display their total numbers. The deviceCount array structure is as follows: [ { " ...

Dealing with Cross-Origin Resource Sharing (CORS) issue in an Angular 6 and .Net Core

A project was recently completed involving the development of a .Net Core MVC (angular) app and a .net core Api app CORS has been enabled in both the Web app and API .Net Core services.AddCors(options => { options.AddPolicy("Cor ...

Storing an array in a file using Swift

In the process of developing an application, I have successfully implemented functionality to: Check for an internet connection; Receive a JSON file from the server and store the data in a file if the server is reachable; Read from the file if the connec ...