为什么更改组件属性的值会自动更改相应的服务属性?

Why does changing the value of a component property automatically change the corresponding service property?

我正在开发一个 angular2 应用程序,它利用多种服务在整个应用程序中共享日期。

在我的应用程序的一部分中,我有一个编辑功能,允许用户修改数组中的数据。

这样的话,当用户在组件中修改了一个属性,服务中相应的数据也被修改了,不用直接设置。

我用了大约 6 个月的时间来学习 angular,但我知道将一个数组设置为等于另一个数组实际上是指向同一个对象。所以在这种情况下,我在服务中有一个方法 returns 数组作为 slice(),我认为应该创建新数组以避免用户直接修改服务数据。

我正在开发的完整应用程序相当复杂,但我能够创建一个简单的框架 angular 应用程序来演示正在发生的事情。

test.component.html:

<div *ngFor="let item of testComponentData">
      <p>{{ item.fname }} {{ item.lname }} <button (click)="onUpdate(item.id)">Update</button></p>
</div>

test.model.ts:

export class TestObject {
  constructor(public id: string, public fname: string, public lname: string) {}

test.service.ts:

@Injectable()
export class TestService {

  constructor() { }


  private serviceData: TestObject[] = [
    new TestObject('1', 'Joe', 'Smith'),
    new TestObject('2', 'Mary', 'Jones'),
    new TestObject('3', 'Larry', 'Murray'),
  ];

  getData() {
    return this.serviceData.slice();
  }
}

test.component.ts:

export class TestComponent implements OnInit {
  testComponentData: TestObject[];

  constructor(private testService: TestService) { }

  ngOnInit() {
    this.testComponentData = this.testService.getData();
  }

  onUpdate(id) {

    // Clicked 3rd button, id = 3

    const temp = this.testComponentData.find(o => o.id === id);

    console.log(this.testService.getData());

    // 0: TestObject {id: "1", fname: "Joe", lname: "Smith"}
    // 1: TestObject {id: "2", fname: "Mary", lname: "Jones"}
    // 2: TestObject {id: "3", fname: "Larry", lname: "Murray"

    setTimeout(() => {
      temp.fname = 'Bartholomew';
      console.log(this.testService.getData());
    }, 5000);

    // 0: TestObject {id: "1", fname: "Joe", lname: "Smith"}
    // 1: TestObject {id: "2", fname: "Mary", lname: "Jones"}
    // 2: TestObject {id: "3", fname: "Bartholomew", lname: "Murray"}

  }

}

在组件中,testComponentData属性在ngOnInit中通过调用testService.getData()方法初始化,其中returnsthis.serviceData.slice()

在此示例中,我单击第 3 个按钮将 fname 设置为 'Bartholomew.' 正如您在嵌入式评论中看到的那样,testService 数据发生了变化,即使我只是更改了组件对象 (testComponentData) , 服务数据也正在改变 (this.testService.getData())

超时只是在那里,因为有时第一个 console.log 是滞后的,日志将显示该值已经更改。

我这辈子都看不出这是怎么回事。我知道这里有一些基本的东西,我假设我正在以某种方式访问​​同一个对象,但我不明白为什么。

感谢任何帮助。谢谢!

这是因为Array.slice on an array of objects is creating a new array who's values are references to the original objects. You will not see this functionality with something like a string or number array. You can get more information from 关于浅拷贝数组。

.slice() 调用是复制数组的已知快捷方式。类似于使用扩展 [...someArray] 运算符。但是,由于数组的内容是对象,它们通过引用返回到新数组中。

Basically, both the arrays i.e. serviceData in service and temp in component are sharing the same object references.

因此更新 temp 中的项目值也反映在 serviceData 数组中。

对象会因为同一个对象的引用而改变。如果您不想影响原始对象,现在需要克隆。尝试以下代码

声明克隆数组:

clonedTestComponentData: TestObject[];

克隆数组:

const this.clonedTestComponentData  = Object.assign([], this.testComponentData);

克隆一个对象:

const temp = Object.assign({}, this.testComponentData.find(o => o.id === id));