Search code examples
typescriptionic-frameworkpass-by-referencepass-by-valuereturn-by-value

ionic 3 typescript : passing object between pages by value


I'm working on an Ionic 3 Application and I have a page which list items if we click on an item it goes to page item update

The page item update contains an update button, but when I updated some input and I return back without clicking on the update button, I found the item already updated

So I think that the problem was that I'm passing the item by reference:

Code:

items page template (item = recipe here) : recipes.html

  <button ion-item *ngFor="let recipe of recipes" [navPush]="recipePage" [navParams]="recipe">
      <h2>{{recipe.title}}</h2>
      <p>{{recipe.difficulty}}</p>
  </button> 

item details page component: recipe.ts

  ionViewDidLoad(){

      this.recipe = this.navParams.data ;

  }

Question how can I pass the recipe with value and not with reference please ?


Solution

  • As kriss said you should create a deep copy of your object. Something like this:

      ionViewDidLoad() {
        this.originalRecipe = this.navParams.data ;
        this.recipe =  Object.assign({}, this.originalRecipe);
      };
    
      update(){
        this.originalRecipe = this.recipe;
      };