changing the component object, effecting service object

html

<button *ngFor="let mstore of selectedStores;let i = index" mat-menu-item  (click) = "$event.stopPropagation()">
        <mat-checkbox class="example-margin" (change)="onChange($event,i)" [checked]="mstore.shiva" style="padding: 0%;">{{mstore.name}}</mat-checkbox>
      </button>

component

selectedStores :headerStores[];
 this.userService.getUserDetailsById(this._jwtModel.id).subscribe(data=>{
      this.userDetails = data;
      this.headerService.addStores(this.userDetails.stores);
      this.selectedStores = this.headerService.getSelectedStores(); 
    });

service

import { Injectable } from '@angular/core';
import { storeModel } from '../store/store.model';
import { headerStores } from './header.store.model';

@Injectable({
  providedIn: 'root'
})
export class HeaderService {

  myStores:headerStores[];

  constructor() { }

  addStores(stores : storeModel[]){
    this.myStores = [];
    for( const store of stores){
      let item ={
        "id" : store.id,
        "shiva" : true,
        "name" : store.name

      }
      this.myStores.push(item);
    }
  }

  getSelectedStores(){
    console.log("mystores"+JSON.stringify(this.myStores));
    return this.myStores.slice();
  }
}

Model

export class headerStores{
    public id : number;
    public shiva : boolean;
    public name : string;

}

In service mystores getting changed when I am checked/unchecked checkboxes. Usually shoud effect only in selectedStores object , but not able to trace why myStores getting effected in service. When I am changing the checkbox selection only selectedstores should get effected

Upvotes: 0

Views: 14

Answers (1)

AliF50
AliF50

Reputation: 18859

The stores are an array of objects and both arrays and objects are reference types so you have to return a copy of both the array and the object.

I would do this:

getSelectedStores(){
    console.log("mystores"+JSON.stringify(this.myStores));
    // map will transform the array and return a new array
    // we take the store and return a new object with ({ ...store })
    return this.myStores.map(store => ({ ...store }));
  }

Upvotes: 1

Related Questions