bravik
bravik

Reputation: 460

Private TypeScript class variable returned in getter method is affected in other class?

It's an angular 2 project.

I have a class with static cities data:

export class CityService {    
    private availableCities: City[] = [];

    constructor() {
        this.availableCities.push(new City('london', 'London'));
        this.availableCities.push(new City('paris', 'Paris'));
    }

    getAll() {
        return this.availableCities;
    };
}

I have another class using it:

export class NavbarComponent {
    private cities: City[];
    private currentCity : City;

    constructor(private cityService: CityService) {
        this.cities = cityService.getAll();
        this.currentCity = cityService.getCurrent();
        this.cities.forEach((city, index) => {
            if (city.name == this.currentCity.name) {
                //@todo BUG This affects private cities variable in CityService class WTF!!!!!!!
                this.cities.splice(index, 1);
                return;
            }
        })
    }

}

So in constructor of this class I'm trying to load all cities with getAll() method. These cities are loaded into NavbarComponent own private cities variable. However when I do manipulate with NavbarComponent's cities var - it changes CityService's cities private property! Why???????? That ruins my perception of the wold!

Can anybody explain and give links to do some reading why that happens

TypeScript version 2.1.5

Upvotes: 0

Views: 311

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68635

You have returned a reference of that cities. So you have one object with two references and if you change it from one, it will be changed also for the second. In this case you can use slice() function instead of splice(), because splice actually changes the array.

this.cities = this.cities.slice(index, 1);

Upvotes: 1

Related Questions