In Angular 5, the array.length property may show as undefined in the console, even though the actual

I have been able to successfully retrieve values from my local APIs (laravel) and store the data in variables, which is displayed in the views. However, when I attempt to calculate the number of live and idle devices by determining their length or accessing specific properties, it returns 0 for the length and undefined when trying to access properties. Below are the code snippets. What could be causing this issue and how can it be resolved?

My dashboard.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { UserDevices } from '../../interfaces/user-devices';
import { LiveRecord } from '../../interfaces/live-record';
import { HistoryRecord } from '../../interfaces/history-record';
import { Timestamp } from 'rxjs';
import { LiveRecordModule } from '../../models/live-record/live-record.module';
import { LiveRecords } from '../../models/LiveRecords';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  user_id: number;
  token: string;
  myDevices: number[]=[];
  myLiveRecords: LiveRecord[] = [];
  myHistoryRecords: HistoryRecord[] = [];

  runningDevices: number[] =[];
  idleDevices: number[] = [];
  stoppedDevices: number[] =[];
  inactiveDevices: number[] =[];
  devicesWithNoData: number[] =[];

  constructor(private httpClient : HttpClient) { }

  ngOnInit() {
    this.user_id = +localStorage.getItem('id');
    this.token = localStorage.getItem('token');
    this.getMyDevices(this.user_id);
    console.log(this.myDevices);                        //working

    console.log(this.myLiveRecords);                    //working
    console.log(this.myHistoryRecords);                 //working

    console.log(this.myLiveRecords.length);             // 0
    console.log(this.myLiveRecords[0].deviceId);        // Error

    this.myLiveRecords.forEach(record=>{                // not working
      console.log("record found: " + record.deviceId);
    });
    for(let record in this.myLiveRecords){              // not working
      console.log(record);
    }
  }

  getMyDevices(user_id:number){
    let promise = new Promise((resolve, reject) => {
      this.httpClient.get<number[]>("http://localhost:8000/api/getMyDevices/"+this.user_id+"?token="+this.token)
        .toPromise()
        .then(
          res => { // Success
            for(let i=0; i<res.length;i++){
              this.myDevices.push(res[i]);
              this.httpClient.get<LiveRecord>("http://localhost:8000/api/getDeviceLiveRecord/"+res[i]+"?token="+this.token)
              .toPromise()
              .then(
                res => { // Success
                  if(res!=null)
                    this.myLiveRecords.push(res[0]);
                  else
                    this.myLiveRecords.push(null);
                  //console.log(res);
                  resolve();
                },
                msg => { // Error
                reject(msg);
                }
              );
              this.httpClient.get<HistoryRecord>("http://localhost:8000/api/getDeviceHistoryRecord/"+res[i]+"?token="+this.token)
              .toPromise()
              .then(
                res => { // Success
                  if(res !=null)
                    this.myHistoryRecords.push(res[0]);
                  else
                    this.myHistoryRecords.push(null);
                  //console.log(res);
                  resolve();
                },
                msg => { // Error
                reject(msg);
                }
              );
            }
            resolve();
          },
          msg => { // Error
          reject(msg);
          }
        );
    });
    return promise;    
  }
}

My dashboard.component.html

<div class="deviceInfo">
    <div class="row">
        <div class="col-md-2" style="background:green; height:50px">
            <span>Running</span>
        </div>
        <div class="col-md-2" style="background:yellow; height:50px">
            <span>Idle</span>
        </div>
        <div class="col-md-2" style="background:red; height:50px">
            <span>Stopped</span>
        </div>
        <div class="col-md-2" style="background:grey; height:50px">
            <span>Inactive</span>
        </div>
        <div class="col-md-2" style="background:black; height:50px">
            <span>No Data</span>
            <p>{{devicesWithNoData.length}}</p>
        </div>
    </div>
</div>
<div class="row">
    <table>
        <thead>
            <td>S.N</td>
            <td>DeviceID</td>
            <td>Last Live</td>
        </thead>
        <tbody>
            <tr *ngFor="let live of myLiveRecords;let i =index">
                <td>{{i+1}}</td>
                <td>{{live?.deviceId?live.deviceId:myDevices[i]}}</td>
                <td>{{live?.recordDate?live.recordDate:"No Data"}}</td>
            </tr>

        </tbody>
    </table>
</div>

This is what appears in the browser: output with console

Answer №1

https://i.sstatic.net/7X0wk.png The issue lies within.

{{live?.deviceId?live.deviceId:myDevices[i]}} <--- Conditional Operator ?

Have you defined the deviceId variable using var or let like this: let deviceId = xxxxx; Create a watch in Google to check if this variable is present.

It's not straightforward to pinpoint. This code is written in TypeScript but should be converted to JavaScript version 6 or 5.

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

Extracting type from a variable in TypeScript

class A { public static find(): Query{ const f = () => new this(); return new Query(f); } } class B extends A { } class C extends A { } class Query { private readonly entity: () => A; constructor(entity: () => A) { ...

Exploring methods to access specific values from an array containing multiple values using Lodash in Angular 4

Hey, I have an array that looks like this: [ 0: "Migration, MD" 1: "Lution, MD" 2: "Mover, MD" 3: "Dee" 4: "Prov10A" ] I would like to extract the values that contain the word "MD" in them. In other words, I want a result like this: [ 0: "Migratio ...

Nestjs: Can't find property in Mongoose document

I am currently encountering some issues with the following code while using Nestjs along with Mongoose: import { Injectable } from '@nestjs/common'; import { Key, KeyDocument } from '@app/mongo'; import { Model } from 'mongoose&apo ...

Using Typescript to define classes without a constructor function

As I was going through the "Tour of Heroes" guide on the Angular website, I came across the following code snippet: class Hero { id: number, name: string, } const aHero: Hero = { id: 1, name: 'Superman' } console.log(aHero instanceof H ...

The issue with calling a public method from an onchange event triggered by a custom Google Maps control in the Ionic framework has been encountered

Hello, fellow developers! I am relatively new to Ionic and web programming in general. Currently, I am working on a small app that involves integrating the Google Maps JS API. While I have successfully created and loaded the map, as well as added a custom ...

A declaration file for the module 'module-name' was not found. The file '/path/to/module-name.js' is assumed to have a type of 'any' by default

After diving into the inner workings of TypeScript module resolution, I stumbled upon an issue. Within my repository @ts-stack/di, the directory structure post-compilation looks like this: ├── dist │   ├── annotations.d.ts │   ├─ ...

Disregarding axios error due to invalid certificates while developing a visual studio code extension

I'm currently developing a Visual Studio Code extension that involves making HTTPS GET requests. I'm working on ignoring invalid certificates, specifically expired certificates. Below is a simple TypeScript script that successfully achieves this ...

What is the technique for retrieving variable types from beyond the function's scope?

I am facing a challenge with a function where I have declared a variable with a somewhat complex structure: export function foo() { const myVar = { // some properties with complex types here... } // Do something with `myVar` } Now, I ...

Converting information from one form to another using Typescript

I am in need of transforming data received from BE into a different format so that it can be inserted into a table component. The original format looks like this: { "displayName": "Income", "baseVersionSum": null, ...

Utilize the type definition from a comparable package

Incorporating fabric-with-gestures into my Typescript project has been smooth sailing so far. However, I've encountered a hurdle when trying to utilize the types defined in the original library fabric. Although I can easily install them using npm inst ...

How to display ngx-toastr using the show() method in Angular 2+ with a specific type

Working with ToastrService.success/error/warning/info() poses no issues for me, However, when attempting to utilize ToastrService.show(), I am unsure of the correct string type to pass along I made an attempt by sending an enum like so: export enum To ...

What defines the category of a component in Angular 13?

As I work on creating a component that accepts another component as an input, I encountered a situation where I needed to define the input type correctly. You can check out a demo of this in action here on StackBlitz. In the @Input() section of the ParentC ...

@The value of @Input is consistently undefined

I'm using @Input to pass IDs into a child component, where they are used to filter the data set within that component. <div *ngIf="exerciseLength > 0"> <exercise [course]="Course" [filter-by-exercise-id]=""></exercise> </di ...

You haven't included an index signature in the TypeScript type

I am creating MyInterface.dic to function as a dictionary with the format name: value, and here is how it is defined: interface MyInterface { dic: { [name: string]: number } } Next, I am writing a function that expects my specific type: function foo(a ...

What are the advantages of utilizing the HttpParams object for integrating query parameters into angular requests?

After exploring different ways to include query parameters in HTTP requests using Angular, I found two methods but struggled to determine which one would be the most suitable for my application. Option 1 involves appending the query parameters directly to ...

Encountering an issue during Angular upgrade from version 8 to 11: Error message stating that the class extends value is undefined,

I am currently in the process of upgrading my Angular application from version 8 to 11, but I encountered the following error: Uncaught TypeError: Class extends value undefined is not a constructor or null at Module.4lR8 (main.js:sourcemap:59) at _ ...

The data type 'string | null | undefined' cannot be assigned to the data type 'string | undefined'

In my Angular application using Typescript, I have the following setup: userId?: number; token?: string; constructor(private route: ActivatedRoute) { this.route.queryParamMap.subscribe( (value: ParamMap) => { this.userId = val ...

Conceal particular information within a repeated sequence and reveal it within a secret panel

I am working on a component that needs to show a hidden form when a specific content is clicked. I have successfully achieved this functionality, but now I also need to hide the original content div and display the hidden form in its place without affect ...

What steps can be taken to ensure that typescript exports remain backward compatible with module.exports?

I initially defined a node.js module in the following way: function sayHello(){ // do something } module.exports = sayHello; After transitioning to typescript, I created sayHello.ts like this: function sayHello():void { // do something } export de ...

The 'X' property is not found in the DefaultRootState type, even though it is declared in the corresponding Interface

Below is the Interface being used in conjunction with mapStateToProps: export interface IStore { cache?: any; dataManager?: IUR; userPrefs: IUP; IModal?: IfingerprintModal; } export interface IModal { cbCancel: IFModalFn | null; cbTryAgain?: I ...