【问题标题】:ERROR TypeError: Cannot set property 'month' of undefined错误类型错误:无法设置未定义的属性“月”
【发布时间】:2018-04-20 02:06:53
【问题描述】:

即使 Visual Studio 代码没有给我任何错误,我也以某种方式在 chrome 的控制台中收到了该错误。

这是我在 interfaces.ts 中的代码

export interface Data1{
month: string;
employeeName: string;
date: string;
employmentStatus: string[];

}

这是我在 tables.component.ts 中的代码

import { Component, OnInit } from '@angular/core';
import { Data1 } from '../../../shared/interfaces';

@Component({
  selector: 'app-tables',
  templateUrl: './tables.component.html',
  styleUrls: ['./tables.component.css']
})
export class TablesComponent implements OnInit {
  today = new Date();
  dataForTable1: Data1;
  months: string[] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
  ]

  constructor() { 
    console.log(this.today.getMonth());
    console.log(this.months[this.today.getMonth()]);
    this.dataForTable1.month = this.months[this.today.getMonth()]
    this.dataForTable1.employeeName = '';
    this.dataForTable1.date = this.today.getDate().toLocaleString();
    this.dataForTable1.employmentStatus = [''];
  }
  ngOnInit() {
  }

}

我尝试使用 console.log 进行调试,但它给了我正确的输出,但我不知道为什么它说未定义。 我目前正在使用 Angular CLI:1.7.4;节点:8.11.1;打字稿:2.8.1 希望有人可以提供帮助。

【问题讨论】:

  • 您没有从 Typescript 收到编译时错误的原因是该错误是运行时错误(类似于 C# 中的对象引用错误)。

标签: javascript angular typescript


【解决方案1】:

您需要将 Data1 定义为类而不是接口,或者您需要基于该接口定义一个具体的类。然后实例化它,以便您可以使用它的属性。

this.dataForTable1 = new SambleClass() 

【讨论】:

  • 成功了!但是在我之前的项目中,我使用和接口并使用它的方式与我在这个项目中使用的方式相同。唯一的区别是我将接口用作像 products: IProduct[] = [] 这样的数组,它可以工作。这是否有效,因为 products 是用 = [] 初始化的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
  • 2019-10-14
相关资源
最近更新 更多