Reputation: 163
I'm quite new to Angular, and I'm trying to display some data that is being retrieved from an API. I'm using Angular 5 and Observables. When I make multiple calls to retrieve the data, my list isn't refreshed (replaced) with the new data, the data is duplicated. I have done what I can to ensure that the underlying array doesn't contain duplicate data.
Here is my method to get the list of players:
getPlayersByTeam(teamId:string) {
console.log("Calling eval /player/roster/" + teamId);
this.httpClient.get<Player[]>(this.evalServerBase + this.rosterUrl + teamId).subscribe(
data => {
this.players = data as Player[];
console.log("EVAL SERVICE PLAYERS " + this.players.length);
this.data.setPlayers(this.players);
},
success => {
console.log("Successfully Completed getPlayersByTeam");
console.log(success);
}
);
}
My data service contains this:
private playersSource = new BehaviorSubject<Player[]>(null);
currentPlayers = this.playersSource.asObservable();
and
setPlayers(players:Player[]) {
this.playersSource.next(players);
console.log("DATA SERVICE PLAYERS " + this.playersSource.value.length );
}
This is some code in my playerselector.component.ts file:
currentPlayers:Player[];
ngOnInit() {
console.log("Init in playerselector.ts");
this.data.currentPlayers.subscribe(currentPlayers => this.currentPlayers = currentPlayers);
}
And here is my playerselector.component.html file:
<div *ngIf="currentPlayers.length < 1">
No Players
</div>
<div *ngIf="currentPlayers.length > 0" >
Hello:{{currentPlayers.length}}
<ul class="Player" >
<li *ngFor="let currentPlayer of currentPlayers; let i = index" class="Player" >
<div>
{{currentPlayer.lastName}} - {{i}} - {{currentPlayers.length}}
</div>
</li>
</ul>
</div>
I have checked everything data related and there are only 4 elements in the array. In the images I'm displaying the indexes for each element and the array size, so I'm pretty certain the data is correct.
Why is my list duplicating? Any advice greatly appreciated.
Upvotes: 0
Views: 150
Reputation: 2486
As I can see the data in your array is perfectly fine and still having this issue, it means it has to do something with the view layer rather than your data.
This usually happens due to an angular bug, sometimes when certain aspect of your code breaks, angular doesn't clear the previous view and instead appends the new view layer.
Check your console and get rid of any errors, that should fix it.
Upvotes: 1