简体   繁体   中英

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. I added a new array parameter in @Input called additionalValues . Now I need to concat values in new parameters with passed value to data . 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:

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

I tried to print value of _data array in getter method and it's ok. I also tried to print _data at the and of setter method but it's always ok.

I think that the only missing thing is just to to update your data content when the additionalValues input changes :

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

Or wait until the next setter call to get the data updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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