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!