The property of the Angular Typescript object is distinctly not defined, yet the property itself is

Currently facing a bizarre issue.

Even though the console displays data in an object from a subscribed observable, TypeScript code shows it as undefined.

Take a look:

initData(): void {

    this.backendService.getData().subscribe((depotDays: DepotDayAcc[]) => {

      console.log(depotDays)
      console.log(depotDays[0])
      console.log(depotDays[0].investment)
      console.log(depotDays[0]["day"])

      console.log('depotDays[0] == undefined', depotDays[0] == undefined)
      console.log('depotDays[0].investment == undefined', depotDays[0].investment == undefined)
    })
}

https://i.sstatic.net/bOBNN.png

constructor(
    public day: Date,
    public investment: number = -1,
    public profit: number = 0,
    public value: number = 0,
    public percent: number = 0,
    public tickers: Set<string> = new Set<string>()) {
}

Answer №1

ShamPooSham mentioned in a previous comment that your data consists entirely of strings. It appears you are working with an array of strings, not objects.

const firstDay = JSON.parse(days[0]);
console.log(firstDay.investment);

You have two options: fix the payload so it can be deserialized correctly, or manually deserialize each entry.

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

Has anyone tried using the JSON1 extension with Angular in an Ionic project?

Looking to extract SQlite information in JSON layout utilizing the JSON1 extension. Yet, upon trying to execute the code, an error message appears. Error {"message":"sqlite3_prepare_v2 failure: no such function: json_object", "co ...

Why is the selected option not visible in the Angular 8 drop-down?

This is a commonly asked question, but my situation seems to be unique. None of the existing answers have provided a solution for my specific issue. Here is the code that I am working with: <form (ngSubmit)="getExceptions(f)" #f="ngForm"> ...

Primary source for recurring components with the @SkipSelf decorator

Trying to understand the inner workings of Angular's dependency injection system, it seems that the component instance tree is traversed to locate the first occurrence of the specified provider, giving priority to ElementInjector over ModuleInjector ( ...

Putting VueJS, typescript, and jest to the test: examining the contents of a dropdown list web-component

Currently, I am in the process of testing a dropdown list within a web component utilized in a VueJS application. My main focus is on checking whether the dropdown list actually contains items fetched through an HTTP query (handled in a vuex store) once t ...

Angular 2+ Service for tracking application modifications and sending them to the server

Currently I am facing a challenge in my Angular 4 project regarding the implementation of the following functionality. The Process: Users interact with the application and it undergoes changes These modifications are stored locally using loca ...

Having trouble retrieving the Angular CLI version even after ensuring all the necessary requirements are installed?

I am facing challenges with using the Angular CLI. I have successfully installed Node, NPM, and Angular, as confirmed by running the which command in the terminal showing their locations in /user/local/bin. The current version of my node.js is v11.8.0. T ...

Is it feasible to implement early-return typeguards in Typescript?

There are instances where I find myself needing to perform type checks on variables within a function before proceeding further. Personally, I try to minimize nesting in my code and often utilize early-return statements to keep the main functionality of a ...

How can I efficiently iterate through the array of index IDs and then iterate individually through the communes, categories, and locations?

Currently, I am developing a nodejs typescript API where I am retrieving an array of objects using a map loop. The data for "communes", "category", and "location" is fetched from another API function based on the issuerId. However, I am facing issues with ...

Angular 5 interception mechanisms

I have been trying to set up interceptors in my Angular 5 project, but unfortunately they are not working. I injected the interceptor in the file app.module.ts, however, I am still encountering errors. Additionally, I added a console.log statement in the i ...

Sharing data between components in Angular 4: How to pass variables and form content to

Perhaps my wording is incorrect. I am filling out a Client Form with the data from an API response within the NgOnInit function. ngOnInit() { this.indexForm = new FormGroup({ name: new FormControl(Validators.required), status: new FormCo ...

Error encountered during installation of Nativescript Post Install Script

While I am comfortable running one of our current projects with Nativescript, I encountered an error when attempting to install it on a new project using the following command: sudo ng new --collection=@nativescript/schematics the-juice-box --shared The ...

Implementing canActivate guard across all routes: A step-by-step guide

I currently have an Angular2 active guard in place to handle redirection to the login page if the user is not logged in: import { Injectable } from "@angular/core"; import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from ...

What's the Advantage of Using a Getter for a Public Field in Angular?

Having come from a background in Java where the practice is to make variables as private as possible, I've noticed in Angular that private fields are not used frequently. What is the reasoning behind not making fields private if it's possible? ...

Retrieve a specific subset of a union based on the class in a generic function

This question shares similarities with another post I made, but this time focusing on using classes instead of plain objects. class Exception1 extends Error { constructor(message: string, public arg1: string) { super(message); } } class Ex ...

Eslint for Typescript in Vue is throwing an error with a message "Unexpected token, expecting ','. Make sure to

Whenever I attempted to utilize vue's type assertion, I kept encountering this eslint error. To illustrate, consider the following snippet: data: function () { return { sellerIdToListings: {} as any, // 'as' Unexpected to ...

The Cordova InAppBrowser plugin has not been properly set up

After running cordova plugin list, I noticed that the InAppBrowser plugin is listed. However, when I try to run my code on an android device, I receive this message in the console via Chrome Remote Debugger: Native: InAppBrowser is not installed or you ar ...

What is the process for initiating a local Lambda edge viewer request?

Is there a way to run aws cloudfront lambda edge functions locally and simulate the event in order to observe the response from one of the four functions? I made modifications to the viewerRequest function of lambdaEdge, but I'm wondering if there is ...

Showing json information in input area using Angular 10

I'm facing an issue with editing a form after pulling data from an API. The values I retrieve are all null, leading to undefined errors. What could be the problem here? Here's what I've tried so far: async ngOnInit(): Promise<void> ...

What reasons underlie the existence of various methods for importing Modules in JavaScript?

I'm confused about the distinctions when it comes to importing a JavaScript module in various ways such as: CommonJS ES5 ES6 NodeJS Typescript What is the reason for having multiple methods of importing JavaScript modules? Is the concept of a "modu ...

Showing particular URL text upon opening a new window using JavaScript

I've encountered an intriguing scenario. In my application, there's a feature that triggers a new window/tab to open when a button is clicked. Upon opening, a predefined HTML page is shown to the user with a specific URL set. I'm curious abo ...