Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ??

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]);
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading