"Angular encountered an error while attempting to access the property 'data' from an undefined

I'm encountering an issue when trying to retrieve data from a JSON file. Upon clicking a button to display the data in a textarea, the first click does not yield any result, but subsequent clicks work as expected. The program functions by fetching an ID from the dashboard and then using that ID to fetch different JSON files for extraction. The program is displaying the following error:

ERROR TypeError: Cannot read property 'data' of undefined at StepService.webpackJsonp.102.StepService.populateList (step.service.ts:69) at CalibrationDetailComponent.webpackJsonp.101.CalibrationDetailComponent.next

step.service.ts

private jsonData: any; //JSON data
public list: String[] = []; //Stores the steps list
public listLength: number; //Number of steps in the list
public listCurrent: number = 0; //Current step within the list

//Retrieves the JSON file
public getJson(): Observable<any> {
    return this.http.get(this.jsonUrl)
      .map(response => response.json());
}

//Subscribes to the JSON
public subScribe2Json() {
    this.getJson().subscribe(data => (this.jsonData = data));
}

//Populates the list with data from the JSON to extract specific steps
public populateList() {
    this.jsonData.data.forEach(element => { //This line causes the error
        this.list.push(element.name);
    });
    this.listLength = this.list.length;
}

//Returns the mainStepText for the current step
public getJsonData(): String {
    this.mainStepText = this.list[this.listCurrent];
    return this.mainStepText;
}

calibration-detail.component.ts

next button method

next() { //Advances to the next step
    this.stepService.subScribe2Json();
    if (this.stepService.listCurrent < 1) { //Ensures that the list is populated only once
        this.stepService.populateList(); //Populates the list from the JSON array
    }
    if (this.stepService.listCurrent < this.stepService.listLength) { //Prevents exceeding the number of steps
        this.stepService.subScribe2Json(); //Subscribe to the list
        this.mainStepText = this.stepService.getJsonData(); //Retrieve data from the list and output it to the main textarea
        this.stepService.listCurrent++; //Increment the step counter

Answer №1

This response provides guidance on how to approach the problem without offering a complete solution. It directs your focus in the right direction based on your objectives.

When you call

this.stepService.subScribe2Json();
if (this.stepService.listCurrent < 1) {
...

The issue arises because the first method is called immediately followed by the second without waiting for the data to be available, leading to failure.

Depending on your requirements, you can consider returning the Observable, possibly transforming it into a Promise, and then:

return this.getJson().subscribe(data => (this.jsonData = data));

Alternatively, you could use something like:

this.stepService.subScribe2Json().then(/* perform necessary actions here */);

or initialize

private jsonData: any = [];

Keep in mind that initializing the data may result in having empty values during the initial run.

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

Utilizing AWS Websockets with lambda triggers to bypass incoming messages and instead resend the most recent message received

I am facing an issue when invoking a lambda that sends data to clients through the websocket API. Instead of sending the actual message or payload, it only sends the last received message. For example: Lambda 1 triggers Lambda 2 with the payload "test1" ...

JQuery Ajax: Issue with updating Total Likes for posts when Like button is clicked

There are two JQuery Ajax calls in this scenario. The first call retrieves user messages from MySQL, along with the number of likes for each message and a button for users to like the message. This initial request is functioning correctly. The second Ajax ...

Do you notice a discrepancy in the number returned by Javascript's Date.getUTCDate() when the time component is set to

Consider the following code snippet: const d = new Date('2010-10-20'); console.log(d.getUTCDate()); If you run this, the console will output 20. However, if you modify the code like so: const d = new Date('2010-10-20'); d.setHours(0, ...

JavaScript JSON YouTube API viewCount function is not functioning correctly

I'm struggling to retrieve the views of a video using JavaScript (Chrome Extension). Here is the code I have so far: $(function() { $.getJSON('http://gdata.youtube.com/feeds/api/videos/H542nLTTbu0?alt=json',function(data) { ...

retrieve Angular data across components using Input

When using fetch to make a request to the reqres api users in app.component, I then share the data with its child component (hello.component) via Input. While I am able to get the correct user names in the child template, I encounter an issue when trying t ...

Passing PHP array to JavaScript and selecting random images from the array

Check out my PHP script below: <?php $all_images = glob("Images/Classes/{*.png, *.PNG}", GLOB_BRACE); echo json_encode($all_images); shuffle($all_images); ?> Here's the JavaScript code I'm using: functio ...

Retrieving data from a jSONobject

I have been working on a web service and encountered an issue with retrieving values from a JSON object. I created a parser class to handle this but ran into a problem where the main object was returning as null, causing the subsequent code to not work pro ...

techniques for synchronizing web service protocols and documents

I posted this query on programmers, but there hasn't been much activity yet... if this isn't the right place, I may just withdraw the question. Currently, I am in the process of creating a web service (PHP+JSON) to synchronize with my iPhone app ...

A Guide to Replacing a json Field with Null and Inserting it into a PostgreSQL Database

I have thoroughly examined the available options discussed in this context, but I find that most of them do not adequately address my specific situation. In my scenario, I import this information into a database where the field is designated as SMALLINT. H ...

How can you modify the starting point of data in jQuery flot?

Currently using Flot to create a graph displaying clicks per minute within the first 60 minutes of short URLs generated at . The graph currently displays data from minute 0 to minute 59. My query is about adjusting the data to start at 1 and end at 59, wh ...

Angular - Dropdown menu fails to display options

I encountered an issue with the JSON response from my Angular-12 API endpoint: { "message": "vehicle Model Detail.", "error": false, "code": 200, "results": { "vehiclemakes": [{ ...

Scenario-specific blueprints

I'm currently facing a challenge in incorporating logic into a dustjs template, and I find it challenging to integrate all the components seamlessly. Here is an example of the JSON data I have: { "names": [{ "name": "User 1", "is ...

What are some methods for retrieving RTK Query data beyond the confines of a component?

In my React Typescript app using RTK Query, I am working on implementing custom selectors. However, I need to fetch data from another endpoint to achieve this: store.dispatch(userApiSlice.endpoints.check.initiate(undefined)) const data = userApiSlice.endpo ...

Challenges Encountered When Loading JQuery DataTable with JSON Data in MVC Framework by Clicking a Button

On my MVC page, I have a JQuery DataTable that needs to be populated when the user clicks the Query Button. This is the structure of my DataTable: <table id="mytable" class="table table-striped table-bordered mt-5"> <thead> <tr> ...

Error message indicating a problem with the JSON format while trying to read .txt files

I'm currently working on a python script that reads all .txt files in a directory and checks if they meet certain conditions specified in the script. I have numerous .txt files formatted as .json but encounter an error message indicating an invalid .j ...

How to utilize "json_encode" function for accessing array elements

I'm currently working on fetching a JSON request from the query string ID, and it seems to be functioning almost correctly. However, an additional array object is being added. $id = $_GET['id']; $result = mysqli_query($con,'SELECT * F ...

What is the best method for installing the most recent 1.1.5 version of is-callable?

After running the command npm install, an error occurred: npm ERR! code ETARGET npm ERR! notarget No matching version found for is-callable@^1.1.5. npm ERR! notarget In most cases you or one of your dependencies are requesting npm ERR! notarget a ...

Could one retrieve the value of a type and save it as a constant?

Can I achieve something similar to this: type YesType = true; const myVar = GetTypeValue<YesType>(); // In this instance, the value true is assigned Is it feasible to assign other fixed values to constant variables like in C++? ...

What is the process for automatically initiating a service when importing a module in Angular?

I am curious about how I can automatically run a service within a module upon importing it, without the need for manual service injection and execution. This functionality is similar to how the RouterModule operates. @NgModule({ imports: [ Browser ...

Update data in several JSON files with extensive sizes

I have a directory filled with numerous large JSON files that I want to enhance for better performance. My approach involved utilizing the gulp tool along with gulp-replace to eliminate unnecessary white space. Within these files lies a significant JSON s ...