0

I'm using an angular service to get a list of inventory items, check to see if an item is in that list, and remove it. However, I don't want to change the service variable itself, just the temporary value I create. Here is my code:

var inventoryItems = InventoryService.all();
console.log("inventorya: ", InventoryService.all());
inventoryItems.splice($index, 1);
console.log("inventoryb: ", InventoryService.all());

I expect InventoryService.all() to return the same value at all times, but it mutates the value returned. I've tried:

var inventoryItems = new Object(InventoryService.all());

but that doesn't appear to work either. What am I doing wrong?

3 Answers 3

2

You can clone the array with angular.copy(). e.g.

var inventoryItems = angular.copy(InventoryService.all());

Or better yet you could copy the array from inside your InventoryService so you don't have to think about it when you are using it

Sign up to request clarification or add additional context in comments.

2 Comments

As a follow up, how would I get it so that anything calling Inventory.all would get updated after I update inventory (on purpose using another function like Inventory.add)
You can't do that. You can either have everything that calls Inventory.all() share the same instance of the array (the way you had it originally) or you can have everything have it's own instance (the angular.copy() way).
0

Sounds like InventoryService.all() returns an array. If you splice the array you alter the contents of the array. Since it's a reference to an array all references reflect those changes. Sounds like what you want is to return a copy of the array.

You can do that by calling Array.slice(). Like so:

var inventoryItems = InventoryService.all().slice();

Comments

0

If InventoryService.all() returns an Object then you are assigning the Object reference to inventoryItems. You have to create a new Object or clone it.

Here's a fiddle for the test: http://jsfiddle.net/ew5hgkpx/

var test1 = testFactory.getObj();
console.log(test1); // returns [1,2]
//var test2 = testFactory.getObj().splice(0,1);
// test1 now return [2]

var test3 = Object.create(testFactory.getObj()).splice(0,1);
// test1 still returns [1,2]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.