代码之家  ›  专栏  ›  技术社区  ›  Chad K

如何修复Angular*ngFor DOM节点泄漏[关闭]

  •  0
  • Chad K  · 技术社区  · 4 年前

    我有一个应用程序,可以在其中轮询服务器并显示结果

    我用*ngFor循环显示结果

    不管出于什么原因,DOM节点一直在堆积,我不知道为什么

    下面是一个最小的例子: stackblitz

    每次获得新数据时,我如何清除这些dom节点?我做错了什么?

    <div class="test" *ngFor="let todo of todos; trackBy: trackByTodo">
      <p class="id">{{todo.title}}</p>
      <p class="status">{{todo.completed}}</p>
    </div>
    
    export class AppComponent implements OnInit, OnDestroy {
      name = 'Angular';
      todos: Todo[] = [];
      timer: any;
    
      constructor(private http: HttpClient) {
      }
    
      ngOnInit() {
        // Get new data every 2 seconds
        if (!this.timer) {
          this.timer = setInterval(() => {
            this.http.get<Todo[]>("https://jsonplaceholder.typicode.com/todos").subscribe(res => { this.todos = res; });
    
          }, 10000);
        }
    
      }
      ngOnDestroy(): void {
          clearInterval(this.timer);
      }
    }
    

    这是Chrome的性能监视器(F12->性能监视器) enter image description here

    0 回复  |  直到 4 年前