简体   繁体   中英

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?

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);
}

您可以执行Object.assing({},this.provider.getGlobalData())来获取该对象的新副本。

Another idea is to use spread operator:

getGlobalData() {
  return { ... this.gvData};
}

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