Telmo Trooper Telmo Trooper -4 years ago 168
TypeScript Question

How does this variable keep getting updated without new attributions?

I have a simple service that keeps a list of users:

export class UsersService {
users = ['Max', 'Anna', 'Chris'];

getUsers() {
return this.users;
}

addUser(username: string) {
this.users.push(username);
}
}


A component that injects it:

export class TestComponent {
myUsers: any[];

constructor(private us: UsersService) {
this.myUsers = us.getUsers();
}

addUser(username: string) {
this.us.addUser(username);
}


And its template with a button that adds a user to the original list:

<p><button (click)="addUser('Bob')">Add Bob</button></p>

<p *ngFor="let user of myUsers">{{user}}</p>


Considering the constructor is only executed once (I've tested it) how does the
myUsers
variable keep getting updated everytime I add another user? There's no other attribution to it outside the constructor and
myUsers
can't possibly be a pointer since I'm clearly using a method to get a copy of the new value.

Answer Source

When you do this.myUsers = us.getUsers(); your this.myUsers property ends up with a reference to the original UsersService.users array, not a copy of the UsersService.users array. That is, TestComponent.myUsers and UsersService.users point to the same array. So if you update UsersService.users, TestComponent.myUsers gets updated too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download