【问题标题】:Not able to save object value in Angular component无法在 Angular 组件中保存对象值
【发布时间】:2022-01-11 10:54:37
【问题描述】:

这是组件类例如:

export class AppComponent {

  categories = {
     country: [],
     author: []
  }

  constructor(){}

  getOptions(options) {
     options.forEach(option => {
        const key = option.name;
        this.categories[key].push(option.value);
     })
  }
  
}

点击按钮时,我从不同的组件调用getOptions(options)。选项的结构如下:

options = [
  {name: 'country', value: 'Germany'},
  {name: 'author', value: 'Franz Kafka'}
]

所以现在this.categories 的值将会更新,所以现在:

this.categories[country] = ["Germany"]
this.categories[author] = ["Frank Kafka"]

每次单击按钮时,options 的值都会发生变化。当我发送新的options 值时,例如:

options = [
  {name: 'country', value: 'Japan'},
  {name: 'author', value: 'Masashi Kishimoto'}
]

this.categories[country] 的旧值由于某种原因没有得到保存。 this.categories[country] 的新值应该是 ["Germany, "Japan"],但数组中只有 ["Japan"]

【问题讨论】:

  • 您是否在代码中的任何位置将 this.categories[country](或 [author])设置为 [ ]?
  • @Mishi Mashina 不,虽然只有声明,但我将它们设置为 [ ],而不是其他任何地方。

标签: javascript angular typescript


【解决方案1】:

我的代码似乎不太好,即使我尝试过 Javascript。我可以建议的是尝试检查 options.value 的真实值。可能存在一些没有价值选项的条目。

let categories = {
     country: [],
     author: []
  }
  
let options = [
  {name: 'country'},
  {name: 'author', value: 'Franz Kafka'},
  {name: 'country', value: 'Japan'},
  {name: 'author', value: 'Masashi Kishimoto'}
]

options.forEach(option => {
        const key = option.name;
        console.log(key);
        if(option.value)
        categories[key].push(option.value);
     })
     
     
 console.log(categories);

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多