Uh oh! An issue occurred: Cannot access values of an undefined property (reading 'valueOf')

I am attempting to loop through the JSON data and extract the start time and end time keys. I have tried two different methods in my API code to achieve this. The console.log is not showing any errors, but the other loop method is causing an error to appear in the console.

Here is a snippet of my show-api.ts code:

import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';

interface Employee {
    Id: String;
    EmployeeName: String;
    StartTimeUtc: String;
    EndTimeUtc: String;
    EntryNotes: String;
    DeletedOn: String;
}

@Component({
selector: 'app-show-api',
templateUrl: './show-api.component.html',
styleUrls: ['./show-api.component.css']
})

export class ShowApiComponent implements OnInit {

li:any;
lis: any=[];

constructor(private http : HttpClient){
    
}

ngOnInit(): void {
    this.http.get('Api of my JSON file')
    .subscribe(Response => {

        if(Response){
            hideloader();
        }

        const employee: Employee[]=Response as Employee[];
        console.log(employee[1].EndTimeUtc.valueOf()) // No error displayed

        for(var i=0;i<1;i++)
        {

          const date1inString=(employee[i].EndTimeUtc.valueOf()); // Error displayed here.

          const date2inString=(employee[i].StartTimeUtc.valueOf()); // Another error displayed here.

          console.log(date1inString);
          console.log(date2inString);

        }   
    });

    function hideloader(){
        document.getElementById('loading')!.style.display = 'none';
    }
}

The console.log is not displaying any errors when showing the date correctly. However, saving it in a variable results in the following error being shown in the console:

core.mjs:6485 ERROR TypeError: Cannot read properties of undefined (reading 'valueOf')
    at Object.next (show-api.component.ts:51:48)
    at ConsumerObserver.next (Subscriber.js:91:1)
    at SafeSubscriber._next (Subscriber.js:60:1)
    at SafeSubscriber.next (Subscriber.js:31:1)
    at map.js:7:1
    at OperatorSubscriber._next (OperatorSubscriber.js:13:1)
    at OperatorSubscriber.next (Subscriber.js:31:1)
    at filter.js:6:50
    at OperatorSubscriber._next (OperatorSubscriber.js:13:1)
    at OperatorSubscriber.next (Subscriber.js:31:1)

Data received from the API:

[
{"Id": "aa",
  "EmployeeName": "bb",
  "StarTimeUtc": "cc",
  "EndTimeUtc": "dd",
  "EntryNotes": "ee",
  "DeletedOn": null },

{"Id": "ff",
  "EmployeeName": "gg",
  "StarTimeUtc": "hh",
  "EndTimeUtc": "ii",
  "EntryNotes": "jj",
  "DeletedOn": null },
]

Answer №1

The information retrieved from the API is missing the StartTimeUtc property, resulting in an attempt to extract a value from an undefined source, hence causing the error.

It appears that there is a minor spelling mistake with "StarTimeUtc" instead of "StartTimeUtc."

Answer №2

It appears that there may be a mistake in your for loop condition.

Please try using the following code snippet instead and update me on the outcome:

for (let i = 0; i < employee.length; i++)

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

Using JSON in Express without the need for BodyParser

Currently, I am working on building a simple express server that can handle incoming JSON through POST requests. However, I have run into an issue where I cannot utilize bodyparser for this task. In the code snippet below, you can see my server setup along ...

Is there a method in Angular to restrict change detection to only the current component and its descendant components?

Is there a way to trigger an event in the child component without traversing the entire component tree from the parent? import { Component } from '@angular/core' @Component({ selector: 'my-app', template: '<b>{{ te ...

Injecting JavaScript object values into dynamically generated modal

I have a JavaScript object that contains various training courses. Each category includes multiple training courses, and each course is associated with a specific category. Currently, I am able to display the title and description of each category in a mo ...

What is the best approach to retrieve a targeted JSON object list within a Flutter application?

Can anyone provide guidance on extracting only the "Image" data from a JSON object using Flutter? { "ID": 2, "Name": "krish", "info": [{ "Time": "07:30:00", &qu ...

Including a CSS link in a .css file is an essential step in styling

Can someone guide me on how to reference the Bootstrap link (https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css) in a .css file within an Angular project? ...

When a function is passed as an argument in Typescript, it may return the window object instead of the constructor

I'm still getting the hang of typescript, and I've come across a situation where a function inside a Class constructor is calling another function, but when trying to access this within sayHelloAgain(), it returns the window object instead. With ...

What steps should I follow to utilize the Ning API in order to develop a feature similar to this?

Click here for a compilation of blog posts This page provides just a simple list of the latest blog entries. For those interested in the technical side, check out this link to the API documentation I don't have much experience with coding. Any assi ...

Retrieving the character 'a' within an ajax function when the data is in Arabic language

I am facing an issue with my api that sends Arabic string data and needs to be displayed on an HTML web form using the jQuery $.ajax method. However, I am encountering a problem where ajax only receives a single character, 'a', in response as sho ...

Encountering an odd occurrence while parsing an HTTParty response

I am currently working on parsing a json response, and I initially thought my code was functioning properly. However, it seems to be exhibiting some unexpected behavior. Below is the method in my controller: def other_properties @response = HTTParty ...

I am continuously encountering a KeyError in Python due to missing data

After spending quite some time trying to solve this on my own, I've hit a wall. My goal is to retrieve data from a json file and display certain information. The URL I'm working with is: https://www.reddit.com/user/clockwork8.json Here's ...

Exploring the deep nested structure of an object array JSON file through mapping

I am currently working on mapping a nested JSON file, but I am encountering some difficulties. When I log the data in the console, it returns as an 'object' and I am unable to go further than that. (Please note that I am still learning JavaScript ...

What steps can I take to fix error TS7015 in my TypeScript, Next.js, and React application when I encounter an index expression that is not a number data type?

I encountered an error stating "Element implicitly has an 'any' type because the index expression is not of type 'number'.ts(7015)" The file I imported is import { useAmazon } from "@context/amazon"; I used it as follows con ...

Moving SVG Module

My goal is to create a custom component that can dynamically load and display the content of an SVG file in its template. So far, I have attempted the following approach: icon.component.ts ... @Component({ selector: 'app-icon', templa ...

What is the best way to send an array of strings through an AJAX call?

Utilizing ajax to send an array of strings to another page has been a bit tricky for me. Here is the array located on nomes.php [ 'Home','A empresa','funcionarios','Quem Somos?','Historia','Inicio&ap ...

Utilizing Typescript for Axios Response

Incorporating Typescript into my project, I encountered a tedious issue while making an API call using axios. The problem lies within handling nested data properly. Despite my belief that I have correctly typed everything, I persistently face a Typescript ...

Implementing Angular with HTML progress bar for interactive client-side features

Exploring the integration of HTML built-in progress bars with Angular: <label for="file">File progress:</label> <progress id="file" max="100" value="70">30%</progress> I am curious about how ...

Creating UI Bootstrap dropdowns using ng-repeat on the fly

As a newcomer to AngularJS and UI Bootstrap, I am facing an issue with adding dropdowns dynamically using ng-repeat. The main problem lies in the fact that when one dropdown is clicked, it triggers all of them simultaneously. It seems like there is some mi ...

Problems with installing ambient typings

I'm having trouble installing some ambient typings on my machine. After upgrading node, it seems like the typings are no longer being found in the dt location. Here is the error message I am encountering: ~/w/r/c/src (master ⚡☡) typings search mo ...

Exploring bugs in Angular 14 through unit testing

After generating a new Angular project using the CLI ng new ..., I encountered an error when running npm test. The error appeared in the browser: and in the console as well: I haven't made any additional changes to the project. I tested with Node ve ...

Navigating from a Card to a new View in Angular

I am currently developing a project using Angular (latest version). Within my application, I have the functionality to dynamically generate bootstrap cards from an Order Array and display them in my "Order-Item-Component through its respective template. ...