【问题标题】:Problem with adding property in map function to an object将映射函数中的属性添加到对象的问题
【发布时间】:2022-12-05 03:02:07
【问题描述】:

请查看此 stackblitz code 并告诉我为什么 ngOninit() 函数中的 user.state 属性存在错误。

  ngOnInit(){
  this.users = this.users.map((user) => {
              `**user.state = 'orig';**`
              return user;
          });
  }

我已经在我安装的可视代码版本中运行了这段代码,但这里也出现了同样的错误。

【问题讨论】:

  • 你有status,但你正在尝试使用state
  • @Konrad 我认为 state 和 status 是不同的属性,如果他们试图在此处添加新属性或设置某些现有属性的值,这是我不明白的。

标签: javascript angular typescript typescript2.0


【解决方案1】:

根据您的示例 stackblitz,我们可以看到您没有为用户数组提供类型。所以 Typescript 语言尝试从数组中获取一些。由于此数组中的对象无法识别state,因此它不适用于打字稿,因此无法应用。

选项1:
向您的对象添加未设置的堆栈属性

    { 
      name: 'Vincent Vega',
      occupation: 'Sceptic',
      membership: 'Admin',
      status: 'Active',
      created_at: '1994-11-03',
      url:'https://www.coditty.com/code/angular-animation-how-to-animate-single-item-from-ngfor-loop?utm_source=Stackblitz&utm_medium=Code&utm_campaign=Animation_List_and_Items',
      state: null
    }

选项 2:
为您的数组使用 Type 并使状态可选


interface User {
  name: string;
  occupation: string;
  membership: string;
  status: string;
  created_at: string;
  url: string;
  state?: string;
}

users: User[] = []

【讨论】:

  • 我不知道为什么有人会在 typescript 的数据对象中添加 html 元素的状态?
猜你喜欢
  • 2014-02-19
  • 2012-01-14
  • 2012-08-24
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
  • 2019-09-20
  • 2012-02-01
  • 2017-03-03
相关资源
最近更新 更多