简体   繁体   English

Typescript getter/setter 属性数组返回错误值

[英]Typescript getter/setter property array returns wrong value

In my component I have an array called data and I need to set value in different parts.在我的组件中,我有一个名为data的数组,我需要在不同的部分设置值。 I added a new array parameter in @Input called additionalValues .我在@Input添加了一个名为additionalValues的新数组参数。 Now I need to concat values in new parameters with passed value to data .现在我需要将新参数中的value与传递给data value连接起来。 This was my code:这是我的代码:

protected data: any[];
protected additionalValues: any[];

I changed my code in this way:我以这种方式更改了我的代码:

private _data: any[] = [];

get data(): any[] {
    return this._data;
}
set data(value) {
    this._data = value;

    if (this.additionalValues != null && this.additionalValues.length > 0) {
        this._data = [...this.additionalValues, ...value];
    }
}

Where's the problem?问题出在哪里? When I try to get value from data I get the size of array instead of values and, when I use the find method, I'll get an error:当我尝试从data获取值时,我得到的是数组的大小而不是值,当我使用find方法时,我会得到一个错误:

this.data.find(x => ...);

I tried to print value of _data array in getter method and it's ok.我尝试在 getter 方法中打印_data数组的值,没问题。 I also tried to print _data at the and of setter method but it's always ok.我也尝试在 setter 方法的 and 中打印_data但它总是可以的。

I think that the only missing thing is just to to update your data content when the additionalValues input changes :我认为唯一缺少的就是在 additionalValues 输入更改时更新您的数据内容:

ngOnChanges(){
    this.data = [] ;
  }

Or wait until the next setter call to get the data updated.或者等到下一次 setter 调用更新数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM