Search code examples
arraysangulartypescriptsubscriptionsubscribe

Stop object/variable changing with subscribe in typescript


I am trying to implement some form validation to my project, of which change detection is a part, whereby if the user is "editing" and they try to navigate away, I want to show a prompt if they have unsaved changes. An issue I am facing is I have an Array that contains data from my database. I then wanted to create a second array, that is given the same data upon the page loading, so that if the user makes changes, the 2 arrays will no longer be the same and I can show the prompt.

However, I am having the problem that my second array is forever the same as the first. I am unsure how to fix this, I tried using an if statement such as:

this.service.memberData(this.memberId).subscribe(data => {
  
  this.firstArray = data;

    if (this.secondArray.length === 0) {
        this.secondArray = data;
    }

});

How can I make it so that secondArray initially takes the value of data, but never changes after this?


Solution

  • You need to clone the array, rather than just referencing the array itself.

    Try this.secondArray = [...data];