0

In my angular application, I have stored categories in a service. In my component I'm removing the first categories from the array and displaying it. The first category is "ALL", and I don't want to display that.

So when I edit the createCategories array in component, the service data also gets changed. How can I keep the original data in service and just manipulate the data in the component?

Below is the code in the component:

this.createCategories = this.myServ.getCategories();
this.createCategories.splice(0, 1);

The service getCategories method:

public getCategories() {
   return this.categories;
}

Now what is happening is every time we call the component one category is removed from the array and also in the service.

Please guide.

Roland Rácz
  • 2,879
  • 3
  • 18
  • 44
Shruti Nair
  • 1,982
  • 8
  • 30
  • 57
  • use this approach for copy your result object and then edit: duplicateObject = JSON.parse(JSON.stringify(originalObject)); – Hasan Fathi Jan 24 '18 at 08:52
  • @Hasan and if the categories are objects with internal functions, your solution throws an error. Not the best one at all. –  Jan 24 '18 at 08:53

1 Answers1

0

You can, for instance, use an array function. Let's try with filter :

public getCategories() {
  return this.myServ.getCategories()
    .filter((el, index, array) => index !== 0);
}

This will return a new array, without the first element.

  • @shruti: `index !== 0` is the conditional statement that is assuming that the "ALL" item is _always_ the first item in the array, and is always there. You might want to be a little more defensive with your coding to prevent bugs creeping in later (i.e. search for "All" instead, or check the ordinal position and the value etc). – Mark Cooper Jan 24 '18 at 08:49
  • Agreed, but he asked to remove the first item of the array. –  Jan 24 '18 at 08:49
  • Yup, but also that he didn't want to display "ALL" :-) – Mark Cooper Jan 24 '18 at 08:51
  • Thanks @trichetriche .I'm inserting ALL at the first position in the categories array.This works for me. – Shruti Nair Jan 24 '18 at 08:56