Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value not reference in Typescript method return

I am working in Ionic3.

I have a function which calls another function from provider.ts and it returns an interface Object.

page.ts

getList(){
  this.localdata = this.provider.getGlobalData();
}

provider.ts

getGlobalData(){
  return this.gvData;
}

Now, any changes made to localdata are also changing gvData in provider.ts. I don't want to copy the reference, just the value. How can I do it?

like image 582
Tapas Mukherjee Avatar asked Mar 29 '26 23:03

Tapas Mukherjee


2 Answers

The following snippet will return a cloned version of your object.

provider.ts

getGlobalData(){
  return JSON.parse(JSON.stringify(this.gvData));
}

You could also do it this way:

page.ts

getList(){
  this.localdata = JSON.parse(this.provider.getGlobalData());
}

provider.ts

getGlobalData(){
  return JSON.stringify(this.gvData);
}
like image 195
Chris Sharp Avatar answered Apr 01 '26 15:04

Chris Sharp


Another idea is to use spread operator:

getGlobalData() {
  return { ... this.gvData};
}
like image 45
Aleksei LItsov Avatar answered Apr 01 '26 14:04

Aleksei LItsov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!