0

I pass an object to a service, changing a property and passing it back. I expected 'tempcard' and 'card' to hold different values after being changed by the service, but they are identical. I confirmed that the service is changing the value. What am I missing?

output:

new call

card (22925)moved: ---before service

79 to 79

card (22925)moved: ---after service

25 to 25

expected:

card (22925)moved: ---before service

79 to 79

card (22925)moved: ---after service

79 to 25

code:

    //card is an object with the board1LaneId set to 79
    console.log('new call')
    let chs = new CardHelperService(card, this.flatTypes, this.auth);
    let tempcard = card;
    console.log('card (' + tempcard.id + ')moved: \n' +
        tempcard.board1LaneId + ' to ' + card.board1LaneId + '\n')

    card = chs.moveLane(dest); //call to my service 

    console.log('card (' + tempcard.id + ')moved: \n' +
          tempcard.board1LaneId + ' to ' + card.board1LaneId + '\n')

service code:

moveLane(dest:string){
   this.card.board1LaneId=25
   return this.card
}
Rilcon42
  • 9,584
  • 18
  • 83
  • 167
  • Why would you expect that? `tempcard` and `card` are the same referenced object. Did you perhaps mean to _clone_ card into tempcard? – Vaughan Hilts Jun 08 '19 at 22:05

2 Answers2

0

I'm go with @Vaughan Hilts answer, but you want to fix simply update line 3 like below

let tempcard = JSON.parse(JSON.stringify(card));

let me know if anything wrong.

Raghul Selvam
  • 314
  • 2
  • 6
-1

You need a deep copy of tempcard

For example, something like:

let tempcard = clone(card);

... where clone is your choice of arbitrary clone function

You should read up on deep cloning here: Deep copying objects in Angular

You should note that a shallow copy might be fine but if you have nested properties, you run into the same issue.

Vaughan Hilts
  • 2,839
  • 1
  • 20
  • 39