Why does Angular Component variable update on service method call?

I have a service method as shown:

import { Injectable } from '@angular/core';
import { of } from 'rxjs';
import Employee from '../model/employee';

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

  employees : Employee[] = [{
    fName : 'Sam',
    lName : 'Johnson',
    age : 32,
    country : 'USA'
  },{
    fName : 'Raghav',
    lName : 'Sharma',
    age : 30,
    country : 'India'
  }];

  constructor() { }

  getEmployees(){
    return of(this.employees);
  }

  addEmployee(employee : Employee){
    this.employees.push(employee);
    return of({
      status : 200,
      message : "Data inserted"
    })
  }

}

I’m subscribing to getEmployees in component A.

  getEmployees(){
    this.sub = this.service.getEmployees().subscribe((response) => {
      this.allEmployees = response;
    })
  }

Component B updates the service array employees using method addEmployee.
Every time it updates the array employees the Component A variable allEmployees gets updates. Why ??

>Solution :

Looks like you are passing around references to a single instance of the array, so all components are referencing the same array.

Try this instead, which will return a copy of the array:

  getEmployees(){
    return of([...this.employees]);
  }

Leave a Reply