假设我有一个服务"DeviceService"我有设备和方法来控制它们
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';
}
}
}
我还有一个组件"AppComponent"我从OnInit
中的服务中检索这些设备ngOnInit() {
this.devices = this.deviceService.devices;
}
然后在AppComponent的HTML模板中显示它们。我还添加了按钮来打开或关闭它们。
在AppComponent。所以我需要实现一些方法来使用这个服务。
switchOn() {
this.deviceService.switchOnAll();
}
switchOff() {
this.deviceService.switchOffAll();
}
当我按下按钮,它工作。但我很难理解为什么。按钮调用switchOn,它从服务调用switchOnAll方法... 但这个switchOnAll方法修改的是DeviceService中的设备数组?那么为什么这些变化是可见的呢?显示的设备数组不是DeviceService中的那个,而是在ngOnInit中初始化的那个。
这两个数组是否可能在此指令之后以某种方式链接?:
ngOnInit() {
this.devices = this.deviceService.devices;
}
看起来就是这样,因为在this.deviceService.devices上做的所有更改都会被跟踪,所以它们也会在this.devices上做。
提前感谢!
因为你把服务的对象引用传递给了组件,所以服务中的数组变量和组件中的数组变量都指向内存中的同一个数组对象。如果您希望它们指向不同的对象,您可能希望使用Array.from( [original array] )
。这将返回数组的一个新的深度副本,而不修改原始数组。