How to reset injected object at view pop in Ionic2?


#1

I’m trying to do the following:

I have an object like this:

let demo_obj = {
    park_name: "Park #01",
    assets:
    [
        {
            id: 1,
            name: "Test #01"
        },
        {
            id: 2,
            name: "Test #02"
        },
        {
            id: 3,
            name: "Test #03"
        }
    ],
        
}

A page loops through the assets objects with an *ngFor listing each asset as a list item.

<ion-list>
  <ion-item *ngFor="let asset of demo_obj.assets" (click)="gotoAsset(asset)">
    <ion-avatar item-left>
      <img [src]="asset.cover_image_public_path">
    </ion-avatar>
    <h2>{{asset.nome}}</h2>
  </ion-item>
</ion-list>

When the user clicks the button the following code gets executed:

gotoAsset(asset) {
    this.navCtrl.push(AssetPage, { asset: asset });
}

This pushes a page displaying the asset details.

When the new page gets on the stack it fetches the asset from the nav params and it makes a backup copy of it stringifying it.

ngOnInit() {
    this.asset = this.navParams.get("asset");
    this.original_asset = JSON.stringify(this.asset);
  }

The user here, can change several properties on the asset. But when he tries to go back without saving changes the app asks the user with a confirmation alert if he is sure to exit loosing changes:

ionViewCanLeave(): boolean {
    if (JSON.stringify(this.asset) === this.original_asset) {
      return true;
    }

    if (this.can_go_back) {
      return true;
    }

    this.askForLeaveConfirmation();
    return false;
  }

private askForLeaveConfirmation() {
    let confirm = this.alertCtrl.create({
      title: 'Do you confirm?',
      message: 'Leaving the page without saving, will reset the resource at its original state. Are you sure?',
      buttons: [
        {
          text: 'Disagree',
          handler: () => {
            console.log('Disagree clicked');
          }
        },
        {
          text: 'Agree',
          handler: () => {
            this.asset = JSON.parse(this.original_asset);
            this.can_go_back = true;
            this.navCtrl.pop();
            console.log('Agree clicked');
          }
        }
      ]
    });
    confirm.present();
  }

At this point if he chooses Agree, the resource gets reseted. All works fine, in fact you can see in a small fraction of time the resource getting reseted before the animation start.

The weird thing happens when the this.navCtrl.pop() gets called. The previous page keeps the changes even if the resource were reseted.

I thought that it’s in some way linked with the previous page since I’m continuously passing the same object between the pages. Where am I doing wrong?