Error Type: Unable to access the X property because it is undefined

I have this Interface that serves as a type for a JSON file:

export interface IIndustrySectors {
  IndustrySector: string;
  isSelected: string;
  dataSubjectCategories:string[];
  dataTypeCategories:string[];
  SubIndustries:[{
    IndustrySector: string;
    isSelected: string;
    dataSubjectCategories:string[];
    dataTypeCategories:string[];
    SubIndustries:[{}]
  }]
}

Additionally, there are two services:

 
 
 // Retrieve all Data from the JSON file
 getMainIndustrySectors(): Observable<IIndustrySectors[]> {
    return this.http.get<IIndustrySectors[]>(this.industrySectorsURL).pipe(
      tap(((data) => console.log('All: ' + data) )),
      catchError(this.handleError)
    );
  }

//Get Specific object 
  getBySector(sector): Observable<IIndustrySectors| undefined> {
    return this.getMainIndustrySectors().pipe(
      map((products: IIndustrySectors[]) => products.find(p => p.IndustrySector === sector)));

  }

Highlighted below is a snippet from the JSON file:

 [
   {
      "IndustrySector":"Accommodation and Food Service Activities",
      "isSelected": "false",
      "dataSubjectCategories":["DS.Employees","DS.Collaborators"],
      "dataTypeCategories":"Personal Data",
      "SubIndustries": [
        {
          "IndustrySector":"Food and Beverage Service Activities",
          "isSelected": "false",
          "dataSubjectCategories":[],
          "dataTypeCategories":[],
          "SubIndustries":[]
        },
        {
          "IndustrySector":"Accommodation",
          "isSelected": "false",
          "dataSubjectCategories":["DS.Minor","DS.Parent","DS.Legal Person","DS.Natural Person","DS.Disable"],
          "dataTypeCategories":[],
          "SubIndustries":[]
        }
      ]
    }
  ]

The issue arises when calling the service "getBySector" using the code below:

this.readjsonService.getBySector(sector).subscribe(response=>{

      if(response.dataSubjectCategories.length > 0)
      {
        for(i=0; i < response.dataSubjectCategories.length;i++ ){
          this.DSofSectores.push(response.dataSubjectCategories[i])
        }
      }
      
      })
Upon checking the typeof the response, it appears to be an object!

An error is thrown:

TypeError: Cannot read property 'dataSubjectCategories' of undefined "

However, the values are still printed out.

What could be causing this?

My goal is to retrieve additional data related to the selected sector in the "response" and populate an array of type string to bind to a dropdown list. While it seems to work fine initially, this image illustrates what happens after selecting the sub-sector:https://i.sstatic.net/wEtlQ.png

Please assist me with this, as I am new to this and getting quite frustrated :(( Thank you.

EDIT: When doing the following check:

 if (response == undefined) {
          throw new Error("sector not found");
        }
        else { .....

The condition passes despite claiming "cannot read undefined".

Answer №1

The search method fails to identify a match, resulting in the observable returning an undefined value.

findByCategory(category): Observable<ICategory | undefined> {
    return this.getCategories().pipe(
        map((items: ICategory[]) => items.find(item => item.Category === category)));
                                                     // ^^^ no matches found
}

Answer №2

When implementing the getBySector service, you mentioned:

products.find(p => p.IndustrySector === sector))

Using the Array#find method will result in undefined if no objects in the array meet the criteria, such as when no products have IndustrySector === sector. This is why the service requires a return type of

Observable<IIndustrySectors|undefined>
.

If this error appears during compilation or in your development environment, it's due to the specified return type, indicating the potential for undefined, necessitating handling that condition. Modifying your code as shown below should resolve the issue:

this.readjsonService.getBySector(sector).subscribe(response => {
  if (response !== undefined) {
    if(response.dataSubjectCategories.length > 0) {
      for(let i = 0; i < response.dataSubjectCategories.length; i++) {
        this.DSofSectores.push(response.dataSubjectCategories[i])
      }
    }
  }
})

Keep in mind that if a non-matching sector is passed at runtime, the for loop will not run.

Answer №3

Issue: Unable to access 'dataSubjectCategories' property of an undefined object.

The error message indicates that you are attempting to retrieve the value of dataSubjectCategories from an undefined object, making response not a valid object.

To resolve this, modify your code to use

response[0].dataSubjectCategories
instead of response.dataSubjectCategories

Demo

var response = [
       {
          "IndustrySector":"Accommodation and Food Service Activities",
          "isSelected": "false",
          "dataSubjectCategories":["DS.Employees","DS.Collaborators"],
          "dataTypeCategories":"Personal Data",
          "SubIndustries": [
            {
              "IndustrySector":"Food and Beverage Service Activities",
              "isSelected": "false",
              "dataSubjectCategories":[],
              "dataTypeCategories":[],
              "SubIndustries":[]
            },
            {
              "IndustrySector":"Accommodation",
              "isSelected": "false",
              "dataSubjectCategories":["DS.Minor","DS.Parent","DS.Legal Person","DS.Natural Person","DS.Disable"],
              "dataTypeCategories":[],
              "SubIndustries":[]
            }
          ]
        }
      ];
      
     var DSofSectores = [];
    if(response[0].dataSubjectCategories.length > 0) {
      for(i=0; i < response[0].dataSubjectCategories.length; i++ ) {
        DSofSectores.push(response[0].dataSubjectCategories[i])
      }
    }
    
    console.log(DSofSectores);

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

Updating values - trigger modifications on each subsequent value [BehaviorSubject.onBeforeNext?]

Let's say we have a basic BehaviorSubject: this.countryOfBirth$ = new BehaviorSubject<CountryEnum>(null); get countryOfBirth() { return this.countryOfBirth$.value; }; set countryOfBirth(val: CountryEnum) { this.countryOfBirth$.next(va ...

Tutorials on separating each element of a JSON array into its individual div

Here is an example of how to display subtopic_id and subtopic_name in separate divs: <div class="myThing"></div> <div class="myThing2"></div> Using jQuery, the following code will retrieve data from getsubtopics.php and populate t ...

Checkbox ensemble computes total score

I am currently working on a project that involves multiple checkbox groups, with each group containing 3 checkboxes labeled as (1, X, 2). My goal is to assign a value of 100% to each group, distributed evenly among the checkboxes within it. The distributio ...

(Critical) Comparing AJAX GET Requests and HTTP GET Requests: identifying the true client

When a typical GET request is made through the browser, it can be said that the browser acts as the client. However, who exactly serves as the client in the case of a GET request via AJAX? Although it still occurs within the browser, I am intrigued to delv ...

Dynamic Element with Mousewheel Event

Simply put, I am attempting to attach a 'mousewheel' event to a div that contains a scrollbar. My code functions properly when used outside of the plugin I developed, but as soon as I convert it into a plugin, it stops working. I tested changing ...

Refreshing a component in Angular/Angular2 using routerLink from the NavBar when already on the current route

When I am on the same route and click again from the navbar, nothing happens. Is there a way to refresh my component directly from the navbar using a method in routerLink? <li [routerLinkActive]="['active']"><a [routerLink]="['/ca ...

Utilizing Node gRPC for seamless transmission of server metadata to clients without any issues

When working from the client side, adding metadata for the server is a simple process: const meta = new grpc.Metadata(); meta.add('xyz', 'okay'); stub.service.Rpc(request, meta, (err, response) => { }); To access the above on the ...

Generating a form structure from json containing repeated inputs: Control with path formArray could not be located

Currently, I am in the process of constructing a form using JSON data. My backend is implemented with Spring Boot, which returns the following object to an Angular frontend: { "controls": [ { "name": "genre", ...

What is the best way to retrieve CoinEx API using access ID and secret key in JavaScript?

Having trouble fetching account information using the CoinEx API and encountering an error. For more information on the API, please visit: API Invocation Description Acquire Market Statistics Inquire Account Info Note : This account is only for test p ...

The component is being mounted twice to ensure that an axios request is made successfully in an asynchronous test. If the component is only mounted once, the test will fail

When making a request to an internal server for data, I am using axios-mock-adapter to mock the response. The response is an array containing 5 items. To pass the test successfully, I have to mount the component twice. Below is the code for my component: ...

What is the best way to call my template's object in Angular?

I am working on a project that involves an array of notifications, which I then add to the template using *ngFor. I need help figuring out how to pass data about the current notification from the template to be able to delete it from the array. Here' ...

The request cannot be processed due to Error 405: Method not permitted

I am trying to send my json data to a specific URL or update the json data on one of my site URLs, but I am encountering a 405 error. Here is the code snippet that I am using. $.post("details", {name: "John", location: "us"}); ...

Certain conditions triggering CORS policy to block Angular requests

Greetings! I have successfully developed an Angular application with a Spring Boot/Spring Security backend by following this informative guide: Within my Controller class, I've implemented a simple method for requesting data: @GetMapping("/t ...

What could be causing my controller to show {{message}} instead of the message that was set up in the configuration

<!DOCTYPE html> <html> <head> <script src="js/angular.js"></script> <script src="js/Script.js"></script> </head> <body ng-app="LoginPage" ng-controller = "LoginPageController"> <form ...

Adjust validation message and minimum value when radio button is altered in Angular application

Seeking a way to dynamically set a validation message and minimum value based on a radio button selection. Currently, there are two radio buttons for either 9 or 18 holes, each with a corresponding input (used in a golf handicap calculator app). The goal i ...

Having trouble with my Angular CLI post request to localhost:3000, could be due to an issue with my Proxy setup

I've set up a basic local API that focuses solely on handling post requests. I'm currently attempting to integrate this post request into my Angular application, but the results are rather puzzling. It seems like there's a misstep on my end, ...

Tips on personalizing the vue-filemanager interface within Laravel

I'm currently utilizing the Laravel file manager package from here, which provides a pre-compiled JS file or allows for direct use of the vue-component through npm from here. Unfortunately, in both options, the front-end is not customizable. I have i ...

"Looking for a way to eliminate the background of an image on NextJS? Learn

https://i.stack.imgur.com/zAsrJ.png When this image is incorporated into a Nextjs rendering, it unexpectedly includes additional content. <div className="flex flex-col items-start justify-start rounded-3xl p-4 bg-boxi w-1/3"> <div cla ...

What is the process for transforming a JSON file into a parser using argparse?

Here is a sample json file: { "model_name_or_path": "microsoft/layoutlmv3-base", "config_name": null, "tokenizer_name": null, "cache_dir": null, "model_revision": "main", "use_auth_token": false } I am looking to convert this JSON ...

The dilemma between installing Electron or installing Electron-Builder: which one

When it comes to installing Electron for an Electron app with React, the method can vary depending on the tutorial. Some tutorials use electron-builder while others do not, but there is little explanation as to why. First: npx create-react-app app cd app ...