简体   繁体   English

angular 中的变量 scope 5

[英]scope of variable in the angular 5

I know it's silly question but would like to know exact scope of variable of this.我知道这是个愚蠢的问题,但想知道这个变量的确切 scope。

I have tried following and if i make any changes in data, response is getting changed too.我尝试过跟踪,如果我对数据进行任何更改,响应也会发生变化。

I have tried following:我试过以下:

private response;
private data;

getdata() {
  this.service.getdata().subscribe((res: any) => {

    if (res) {
      this.response = res;
      this.data = res;
    }
  });
}

If i use data as input parameter for other component and make any changes on that, my this.response is also getting changed.如果我使用数据作为其他组件的输入参数并对其进行任何更改,我的 this.response 也会发生变化。

I am not sure what to do to retain the previous data.我不确定如何保留以前的数据。

Its because both response and data are sharing the same object reference.这是因为响应和数据共享相同的 object 参考。

Your code within if condition is nothing but a shallow copy of each other if 条件下的代码只不过是彼此的浅拷贝

this.response = this.data = res; 

Hence when you change one value the other value also gets changed,因此,当您更改一个值时,另一个值也会更改,

In order to avoid this from happening you can do the following为了避免这种情况发生,您可以执行以下操作

this.data = Object.assign({},res);

OR或者

this.data = {...res}

Read this for more details on shallow copy and deep copy阅读本文以了解有关浅拷贝和深拷贝的更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM