Home > Software engineering >  ERROR TypeError: Cannot read properties of undefined (reading 'valueOf')
ERROR TypeError: Cannot read properties of undefined (reading 'valueOf')

Time:03-03

I am trying to iterate through the JSON data and access the key of start time and end time. In my API code, I have tried 2 ways to do this. Console.log is not showing error but the other loop method is showing an error in the console.

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())//it is not showing error

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

    const date1inString=(employee[i].EndTimeUtc.valueOf());//it is showing error
    
    
    const date2inString=(employee[i].StartTimeUtc.valueOf());//it is showing error
    

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

    }


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

The console.log is not showing an error and displaying the date properly but when I save it in a variable it is showing the following error 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 from 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 },

]

CodePudding user response:

Response Data from API does not have StartTimeUtc. So you are trying to read valueof() of undefined which is giving you this error.

Its a typo StarTimeUtc instead of StartTimeUtc

CodePudding user response:

Check your for loop. I think it's wrong the condition.

Use this, and let me know

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