Search code examples
angulartypescriptundefined

Angular Typescript object property is clearly not undefined but property is


I'm having a rather ridiculous problem.

An object from a subscribed observable has clearly data in it while printing it to the console, but in actual typescript code, says its undefined.

See for yourself:

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)
    })
}

enter image description here

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>()) {
}

Solution

  • As ShamPooSham has noted in his comment, your data is all strings. You have an array of strings, not objects.

    const depotDay = JSON.parse(depotDays[0]);
    console.log(depotDay.investment);
    

    Choices are to either fix the payload so it gets deserialised properly, or to deserialise each entry yourself.