【问题标题】:adding a variable to an array in angular以角度向数组添加变量
【发布时间】:2019-01-22 18:23:00
【问题描述】:

我正在尝试将在我的 .ts 文件中定义的变量用于数组以填充 handsontable 但无法获取值

变量有一个值,因为我已经登录到控制台

console.log("t1 title " ,this.t1Title);

我添加了字符串 t 以查看一些输出,但变量 this.t1Title 不起作用

settingsObj: Handsontable.GridSettings = {
    data: [{id: 1, name: ('t'+ this.t1Title)},
           {id: 2, name: 'me'},
           {id: 3, name: 'me' }
    ],

如果我对字符串 t1Title 进行硬编码,则该变量有效。 我从 ngOnInit() 中的服务获取变量并像这样分配:

    this.t1Title = tAccount['t1Title'];
        console.log("t1 title " ,this.t1Title);

我在使用 Handsontable 时没有得到任何价值:

数据:[{id: 1, name: this.t1Title},{id: 2, name: 'me'},{id: 3, name: 'me' }],

【问题讨论】:

  • 怎么不行?我刚刚在我的应用程序中尝试了类似的代码,它按预期工作。您能否提供更多关于它如何不起作用的信息(它是否未定义?)以及定义上述代码的更多上下文?
  • 您能否将您正在执行该操作的代码添加到问题中(因为 cmets 中的代码格式不是很好。)我会根据目前的信息猜测存在问题在哪里代码正在执行。
  • 您必须在订阅函数中创建 settingsObj。其他想法总是在你的订阅函数中写:this.settingsObj[0].name='t'+this.t1Title
  • 当我像这样在 ngOnInit() 中设置 settingsObj 时
  • 'this.settingsObj['data'] = [{ id: 1, name: 'me' }, { id: 2, name: 'me' }, { id: 3, name: '我' }]'

标签: arrays angular handsontable


【解决方案1】:

可能您的服务正在异步返回 this.t1Title 的值,可能是通过 Observable。

所以,当下面的代码运行时:

settingsObj: Handsontable.GridSettings = {
    data: [{id: 1, name: ('t'+ this.t1Title)},
           {id: 2, name: 'me'},
           {id: 3, name: 'me' }
    ],

this.t1Title 的值尚未填充。

因此,您需要确保仅在服务实际返回值后运行该代码。如果您使用的是 Observable,这将在 subscribe 函数中。

【讨论】:

  • 我确实在 ngOnInit() 中设置了变量:
  • `ngOnInit() { const id = "1"; if (id) { this.tAccountService.get(id).subscribe((tAccount: any) => { if (tAccount) { console.log("we have at account " ,tAccount); this.tAccount = tAccount; this .t1Title = tAccount['t1Title']; console.log("t1 title" ,this.t1Title);`
  • 我尝试在运行上述操作后设置handsontable,但出现错误。我的理解是 ngOnInit 将首先运行。
猜你喜欢
  • 2018-04-30
  • 1970-01-01
  • 2023-03-29
  • 2023-03-18
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多