iJade
iJade

Reputation: 23811

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

Upvotes: 0

Views: 73

Answers (2)

JotaStar
JotaStar

Reputation: 11

Because the this.employees.push(employee); in service change the employees array so it fires the observer of getEmployees in Component A

Upvotes: 0

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

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

Upvotes: 1

Related Questions