I am getting json data by http call and subscribing like:-
this.localService.getdata('url').subscribe(
function (success) {
this.dataa = success;
this.dataa2 = success;
}
);
stackblitz link:- https://stackblitz.com/edit/angular-stackblitz-json-xr7ny8?file=src/app/app.component.ts
1) data.json
value is assigned to variable dataa2
is changed and when
method get2()
is called dataa2
value is changing. Simultaneously, Same
for variable test2
.
2) How can I store data.json
in a variable (eg- dataa2
) without changing its
value in given situation.
3) Why can't I store success in two variables without changing their values. How
to store success data in two variables without affecting each other. Do I
need to subscribe every time for getting a copy of json data?
data.json
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
.html
<button type ="button" (click)="get()">tset</button>
<br/>
<br/>
<br/>
<button type ="button" (click)="get2()">tset2</button>
.ts
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));
}
}