简体   繁体   English

Angular Typescript 对象属性显然不是未定义的,但属性是

[英]Angular Typescript object property is clearly not undefined but property is

Im having a rather ridicolous problem.我有一个相当可笑的问题。

An object from an subscribed observable has clearly data in it, while printing it to console, but in actual code typescript says its undefined.来自订阅的 observable 的对象在将其打印到控制台时清楚地包含其中的数据,但在实际代码中,打字稿表示其未定义。 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)
    })
}

在此处输入图片说明

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

As ShamPooSham has noted in his comment, your data is all strings.正如 ShamPooSham 在评论中指出的那样,您的数据都是字符串。 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.选择是修复有效负载以使其正确反序列化,或者自己反序列化每个条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM