列出项目重复但数据正确

时间:2018-03-11 07:43:27

标签: angular html-lists angular5 ngfor

我对Angular很新,我正在尝试显示从API检索的一些数据。我正在使用Angular 5和Observables。当我进行多次调用以检索数据时,我的列表不会被新数据刷新(替换),数据会被复制。我已尽力确保底层数组不包含重复数据。

以下是获取玩家列表的方法:

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);
   }
 );      
}

我的数据服务包含:

    private playersSource = new BehaviorSubject<Player[]>(null);
    currentPlayers = this.playersSource.asObservable();

     setPlayers(players:Player[]) {
        this.playersSource.next(players);
        console.log("DATA SERVICE PLAYERS " + this.playersSource.value.length );
    }

这是我的playerselector.component.ts文件中的一些代码:

currentPlayers:Player[];

ngOnInit() {
    console.log("Init in playerselector.ts");
     this.data.currentPlayers.subscribe(currentPlayers => this.currentPlayers = currentPlayers);
}

这是我的playerselector.component.html文件:

<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>

On my first call to the API, I get this And on my second call I get this

我检查了所有相关的数据,数组中只有4个元素。在图像中,我正在显示每个元素的索引和数组大小,所以我非常确定数据是正确的。

为什么我的列表会重复?任何建议都非常感谢。

1 个答案:

答案 0 :(得分:1)

正如我所看到的,数组中的数据完全正常并且仍然​​存在此问题,这意味着它必须对视图层而不是数据执行某些操作。

这通常是由于角度错误造成的,有时当代码的某些方面中断时,角度不会清除上一个视图,而是附加新的视图层。

检查您的控制台并清除任何应该修复的错误。