0

Lets say I have a Service "DeviceService" in which I have devices, and methods to control them.

export class DeviceService {
    devices = [
        {
            name: 'TV',
            status: 'off'
        },
        {
            name: 'PC',
            status: 'on'
        }
    ];

    switchOnAll() {
        for (let device of this.devices) {
            device.status = 'on';
        }
    }

    switchOffAll() {
        for (let device of this.devices) {
            device.status = 'off';
        }
    }
}

And I also have a Component "AppComponent" in which I retrieve those devices from the service in the OnInit

ngOnInit() {
    this.devices = this.deviceService.devices;
}

I then proceed to display them in the AppComponent HTML template. I also add buttons to switch them all on, or all off.

In AppComponent.ts I need to implement methods that use the service to do so.

switchOn() {
    this.deviceService.switchOnAll();
}

switchOff() {
    this.deviceService.switchOffAll();
}

When I press the buttons, it works. But I have a hard time understanding why. The button calls switchOn, which calls the switchOnAll method from the service... but this switchOnAll method modifies the devices array that is in the DeviceService, right? Then how come these changes are visible? The devices array that is displayed isn't the one in DeviceService, it's the one that is initialized in ngOnInit.

Is it possible that these two arrays are linked in some way after this instruction? :

ngOnInit() {
    this.devices = this.deviceService.devices;
}

It looks like it's the case, as all changes made on this.deviceService.devices are tracked so they are made on this.devices too.

Thanks in advance!

CelKyo
  • 19
  • 4
  • 2
    because of the object reference! – Aravind Aug 05 '21 at 13:45
  • Reference as a pointer ? Are "this.devices" and "this.deviceService.devices" the same array ? – CelKyo Aug 05 '21 at 13:50
  • 2
    Hello Celkyo, Aravind is right, check the angular documentation of services: https://angular.io/guide/architecture-services and javascript references: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference Also, yes, the this.devices and this.deviceService.devices are same object, but, this.devices is only used inside service. Also 2, you can use a single service tu communicate with other component: https://stackoverflow.com/questions/41958836/angular2-interaction-between-components-using-a-service – Hoch Aug 05 '21 at 13:57

1 Answers1

0

Since you pass the service's object reference into your component, the array variable in the service and the array variable in the component both point to the same array object within memory. If you wanted them to point to different objects, you might want to use Array.from( [original array] ). This will return a new deep copy of the array without modifying the original.