问题
why angular2 is updating all the references of a variable?
Problem Statement: I have a service which returns observable on calling getData method
@Injectable()
export class BuildingService {
constructor(private http: Http){
}
buildings$: Observable<Building[]>;
getData() : Observable<Building[]>{
if (this.buildings$) {
this.buildings$ = this.http.get('http://localhost:8080/buildings')
.map(this.extractData)
.publishReplay(1)
.refCount();
}
return this.buildings$;
}
private extractData(res: Response) {
let body = res.json();
return body;
}
}
in component I'm subscribing to observable returned from getData method and doing some filtering and it is working fine
export class Component1 implements onInit{
constructor(private _buildingService: BuildingService) {}
buildings: Building[] = [];
ngOnInit() {
this._buildingService.getData()
.subscribe(buildings => {
this.buildings = buildings;
this.buildings.forEach((building, index){
if (building.id === 0) {
this.buildings.splice(index, 1);
}
});
});
}
getUnfilteredData() {
this._buildingService.getData()
.subscribe(buildings => {
this.buildings = buildings;
});
}
}
but even when I call getUnfilteredData() also, I am getting previously filtered data. Can somebody please explain why is this behaviour and how to avoid this?
回答1:
You are using .publishReplay(1).refCount();
to cache the data for multiple subscribers which is working. But in your ngOninit
you are taking the original data reference into this.buildings
and splicing it. So your cached data is also affected.
Solution is to slice(make a copy) the array into this.buildings
before filtering.
ngOnInit() {
this._buildingService.getData()
.subscribe(buildings => {
this.buildings = buildings.slice();//slice instead of taking reference
this.buildings.forEach((building, index){
if (building.id === 0) {
this.buildings.splice(index, 1);
}
});
});
}
Or you could do this:
ngOnInit() {
this.buildings = [];
this._buildingService.getData()
.subscribe(buildings => {
buildings.forEach((building){
if (building.id !== 0) {
this.buildings.push(building);
}
});
});
}
来源:https://stackoverflow.com/questions/41458117/angular2-avoid-updating-reference-variable-also