2

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>()) {
}
4
  • You haven't posted any details of the TypeScript message - namely which line you're referring to. Commented Oct 30, 2021 at 20:58
  • 3
    Is your data coming from JSON.parse? If so, then remember that your class constructor you posted will not be invoked - so those properties will not be set unless they're in the JSON. When using JSON.parse (without custom rehydration logic) you must use interface to describe the data you're expecting. (Indeed, the tickers member looks like an Array<String> to me, not a Set (otherwise Chrome would show "tickers": Set(1) instead of ["ADSK"]. Commented Oct 30, 2021 at 21:00
  • Also, TypeScript's type system is based around type erasure: it's a essentially a glorified practical compile-time type-prover: it is not a runtime type-system - so whenever you use runtime type-assertions you lose the hard guarantees that TypeScript provides (and you have to use type-assertions with JSON.parse unless you write type-guards. Commented Oct 30, 2021 at 21:03
  • 3
    Because depotDays[0] is a string, not an object. Your backend is probably encoding it as json twice Commented Oct 30, 2021 at 21:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.