【问题标题】:Access object with dynamic key in Typescript在 Typescript 中使用动态键访问对象
【发布时间】:2017-08-10 09:08:36
【问题描述】:

在使用括号表示法中的动态键时,我无法访问简单对象中的属性。这是我的代码:

import { Component, OnInit } from '@angular/core';
import { DisplayFeederService } from '../../services/display-feeder/display-feeder.service';

interface IData {
  [key: string]: any;
}

@Component({
  selector: 'display',
  templateUrl: './display.component.html',
  styleUrls: ['./display.component.css']
})
export class DisplayComponent implements OnInit {
  measurementValue: any;
  measurementType: any;
  private typesTable: IData = {
    vdc: 'DC Volt'
  };

  constructor(private displayFeederService: DisplayFeederService) {
    this.displayFeederService.displayData$.subscribe(data => {
      this.measurementValue = data.val;
      this.measurementType = this.typesTable[data.type];
      console.log(this.typesTable, data.type, this.typesTable[data.type])
    })
  }

  ngOnInit() {
  }

}

在 console.log 我得到这个:

对象 {vdc: "DC Volt"} "vdc" 未定义

所以我的对象是有效的,动态键是正确的,但是 synatx object[dynamic key] 对我不起作用。如果我尝试像 this.typesTable['vdc'] 那样访问它,它可以工作,但这不是我想要的,因为将来我会有更多的动态键。

你能指导我正确的方向吗? 谢谢

【问题讨论】:

  • data.type的返回类型是什么?
  • 使用服务返回的服务代码和示例 json 更新帖子

标签: angular object typescript interface


【解决方案1】:

所以我的问题是,即使在开发人员工具控制台中它显示为“vdc”,我的微控制器也在发送“vdc\n”。一个空白让我松开了一半的头发。谢谢大家。

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2021-12-14
    • 2020-10-07
    • 2011-10-18
    • 2021-02-27
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多