DOM 除非点击

DOM isn't updating unless it clicked on

我有一个服务,它通过一个简单的获取请求从服务器获取数据,从一个组件订阅它,并将响应分配给组件中的一个变量,该变量映射到 table HTML。当页面加载时,table 为空,当我单击 DOM 中的任意位置时,视图更新并且 table 加载数据

在component.ts

   ngAfterViewInit(): void {
     this.myService.searchAttendanceRecords(5, 1, 'id', 1).subscribe(res => 
       {
         console.log(res); // this works
         this.data = res;
       }
   }

在HTML

  <table class="table">
      <thead>
        <tr>
          <th >Employee</th>
          <th >Date Time</th>
          <th >Latitude</th>
          <th >Longitude</th>
          <th>Driving</th>

        </tr>
      </thead>
      <tbody>


        <ng-container *ngFor="let item of data">
          <tr >
            <td data-title="Employee">{{item.Employee}}</td>
            <td data-title="Date Time">{{item.DateTime}}</td>
            <td data-title="Latitude">{{item.Latitude}}</td>
            <td data-title="Longitude">{{item.Longitude}}</td>
            <td data-title="Driving">{{item.IsDriving}}</td>
          </tr>
        </ng-container>


      </tbody>
    </table>

预期:table 在页面加载或刷新时加载

实际:table 将不会加载,除非我单击 DOM

这通常是由changeDetection.OnPush策略引起的。

https://netbasal.com/a-comprehensive-guide-to-angular-onpush-change-detection-strategy-5bac493074a4?gi=de1aeda3d62c

请完整展示您的@Component 装饰器。

它也可能在父 @Component 装饰器中。

我想你也需要在 ngOnInit 下订阅。

ngOnInit(){
 this.myService.searchAttendanceRecords(5, 1, 'id', 1).subscribe(res => 
   {
     console.log(res); // this works
     this.data = res;
   }
}