Javascript 订阅时如何在变量中存储json值?

Javascript 订阅时如何在变量中存储json值?,javascript,angular,variables,Javascript,Angular,Variables,我通过http调用和订阅获取json数据,如下所示:- this.localService.getdata('url').subscribe( function (success) { this.dataa = success; this.dataa2 = success; } ); stackblitz链接:- 1) data.json值被分配给变量dataa2发生更改时 方法get2()被调用dataa2值正在更改。同时,同样 对于变量test2 2) 如何将data.j

我通过http调用和订阅获取json数据,如下所示:-

this.localService.getdata('url').subscribe(
function (success) {
    this.dataa = success;
    this.dataa2 = success;
}
);
stackblitz链接:-

1)
data.json
值被分配给变量
dataa2
发生更改时 方法
get2()
被调用
dataa2
值正在更改。同时,同样 对于变量
test2

2) 如何将
data.json
存储在变量(例如-
dataa2
)中而不更改其属性 给定情况下的值


3) 为什么我不能将成功存储在两个变量中而不改变它们的值。如何
将成功数据存储在两个变量中而不相互影响。是吗 需要每次订阅才能获得json数据的副本吗

data.json .html
在javascript中为变量赋值时,该变量保留该值的自身副本。将对象指定给变量时,情况并非如此

如果将同一对象指定给2个变量,则引用该对象的所有变量都将看到该对象属性的任何更改

创建对象副本的一种方法,可以在其中单独操作属性,如下所示:

this.dataa2 = Object.assign({}, this.dataa);

不要那样做。取而代之的是,在任何地方都使用Subscribables。为什么我不能在不更改其值的情况下将成功存储在两个变量中呢。为什么每次我都要订阅。如何避免每次订阅。
this.dataa2=Object.assign({},this.dataa)
将制作一个单独的副本,如果您正试图这样做的话do@abney谢谢this.dataa=数据;this.dataa2=data;。为什么不工作?这样做时,您不是在创建数据的副本,而是在创建对已存在对象的引用。
<button type ="button" (click)="get()">tset</button>
<br/>
<br/>
<br/>
<button type ="button" (click)="get2()">tset2</button>
import { data } from './test';

export class AppComponent implements OnInit {
  name = 'Angular';
  dataa:any;
  dataa2:any;

  test ={
    'id':'abc'
  }

  test1:any;
  test2:any;
  constructor() {
  }

     ngOnInit() {
         this.dataa =  data;
        this.dataa2 =  data;

        this.test1 =  this.test;
         this.test2 =  this.test;
     }

  get(){
    this.dataa['userId'] = 2;
     this.dataa['id'] = 2;

      this.test1['id'] = 'I am changed';
  }


  get2(){
    console.log(JSON.stringify(this.dataa));
      console.log(JSON.stringify(this.dataa2));
  // should be===>  this.dataa2 =  {
   //           "userId": 1,
   //            "id": 1,
   //          "title": "delectus aut autem",
   //        "completed": false
   //           }
      console.log(JSON.stringify(this.test1));
      console.log(JSON.stringify(this.test2));
  }
}
this.dataa2 = Object.assign({}, this.dataa);