Search code examples
jsontypescriptreferenceclone

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?


Solution

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