【问题标题】:Create dynamic key and assign value in typescript variable在打字稿变量中创建动态键并赋值
【发布时间】:2018-07-29 12:34:52
【问题描述】:

在我的组件中使用 any[] 创建了变量,根据我的要求,动态值将来自基于该变量的服务必须创建和分配值。

export class CostsComponent implements OnInit {

  public info: any[] = [];
  constructor(private deliverablesService: DeliverablesService, private setupcostsService: SetupcostsService, private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.activatedRoute.params.subscribe((params: Params) => {
      this.setupcostsService.getcostDetails(2940).subscribe(
        data => {
          this.info.col = data.col; // dynamic
          this.info.data = data.data; //dynamic
          console.log('cost Info',data);
        },
        () => { }
      );

    });
  }

在设置this.info.col 时获取Property 'col' does not exist on type 'any[]'。错误。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您将变量初始化为array,如果不使用index,您将无法读取array 属性。因此,您应该将该变量定义为object 而不是array

    尝试public info: any = {}; 而不是public info: any[] = [];

    我希望下面的讨论可以帮助你。

    What is the difference between any and any[ ]?

    【讨论】:

      猜你喜欢
      • 2015-02-15
      • 2023-03-21
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 2020-12-01
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多