Search code examples
angularangular6angular-servicesangular-components

Complex object of Service changes from component after returning from service function in angular 5


Elaborating my question more,

I have a service called hero.service.ts which is being used in a component called hero.component.ts. hero.service.ts contains a variable heros which is an array and contains many items.

I am getting values of heros from hero.service.ts by a function called getHeroes() which returns the variable as return this.heros; and getting the values on component by this.heros = this.heroService.getHeroes().

In my component, listing of heros there in a table. When i delete rows from table it actually deletes from the variable heros of hero.service.ts too.

  • why is this happening ?
  • Why it is returning the variable reference instead just a values.

FYI, i achieved it by returning heros with ... spreading operator like return [...this.heros];. But why service passing reference of variable. please help guys.


Solution

  • In JavaScript, Complex data types like Arrays and Objects, are passed by reference and NOT by value.

    When you returned this.heros; from your service, your component didn't get the heroes Array. It got the reference to the heroes array in memory.

    So essentially at this point, both the heroes properties in your Component as well as in the Service, were pointing to the same Array in memory.

    To fix this when you did return [...this.heros];, this time it spread the elements of the heroes array into a new array that was created on the fly, and then returned the reference to that newly created array to your component.

    That time, the component heroes were pointing to a different array in memory. Hence when you do that, you get the expected outcome where the hero is deleted from the Component Array but not from the service array.

    Here's a StackBlitz for your ref.