Situation
Currently, I am developing a web application using Typescript/Angular2 RC1. In my project, I have two classes - Class1 and Class2. Class1 is an Angular2 service with a variable myVar = [obj1, obj2, obj3]
. On the other hand, Class2 is an Angular2 component where I obtain myLocalVar = class1.myVar
in the constructor by utilizing viewInjector
to inject the service.
Dilemma
In Class2, I perform a copy of myVar
using a push
method which results in a shallow copy (copying objects). This means that myLocalVar
becomes equal to [obj1, obj2, obj3]
where each object has a property like {number:X}
. The issue arises when I modify one item such as: myVar[0] = {number:5}
in Class1. These changes do not reflect in Class2's myLocalVar
and consequently, myLocalVar[0].number
still holds the value of 1
. Strangely, the original array myVar
in Class2 gets updated. It seems that the line
this.myLocalVar.push(this.myVar[int]);
created a deep copy instead of a shallow copy.
Is there any change in the behavior of the push
method in Javascript due to Typescript? If affirmative, what steps should be taken to maintain the reference and execute a shallow copy?
Sample Code
@Injectable()
export class Class1{
public myVar:any[];
constructor(){
this.myVar = [{number: 1}, {number: 2}, {number: 3}];
}
changeVar(newVar):void{
this.myVar[0] = newVar; // newVar = {number: 5}
}
}
@Component({
selector: 'class2',
viewInjector: [Class1],
templateUrl: 'someURL'
})
export class Class2{
private myLocalVar:any[] = [];
constructor(class1: Class1){
this.myVar = class1.myVar;
}
showVars():void{
console.log(this.myLocalVar[0]);
console.log(this.myVar[0]);
}
ngOnInit(){
for(let int = 0; int < this.myVar.length; int++){
this.myLocalVar.push(this.myVar[int]);
}
}
}
The console.log
will display two distinct values: console.log(this.myLocalVar[0])
will output 1
, while console.log(this.myVar[0]);
will showcase 5
after someone calls changeVar()
!
Update
To better understand the issue, you can refer to this Plunker link.
- Click on show, check your console, and observe identical values
- Click on change
- Click on show again to witness different values for
myVar
andmyLocalVar
I require a solution where every time I alter myVar[x]=newObj
, myLocalVar
mirrors that modification. Kindly provide a resolution to this problem if you seek validation for your response.