ERROR TypeError: Cannot read properties of null (reading 'users') ngFor Change Detection

ERROR TypeError: Cannot read properties of null (reading 'users') ngFor Change Detection

在我的列表-users.component.ts中,我使用了private ref: ChangeDetectorRef下面的代码供参考。

export class ListUsersComponent implements OnInit {
  public users: any[];
  constructor(private ref: ChangeDetectorRef,
              private zone: NgZone) {
                this.ref.detectChanges();
  }
  ngOnInit() {
    this.loadUser();
  }
  
  loadUser() {
    const us = this.userService.getUsers('').subscribe(j => {
      this.users = j; //binds the code but does not show on page load
    });
    this.subscriptions.push(us);
  }

  trackByFn(index: number, users: any){
    return users.id;
  }
}

这是我的 HTML 模板 list-users.component.html,如下所示。

<tr align="center" *ngFor="let user of users; index as i; trackBy: trackByFn">
   <td>{{user?.id}}</td>
   <td>{{user?.userName}} </td>
   <td>{{user?.occupation}}</td>
   <td>{{user?.companyName}}</td>
   <td>{{user?.role}}</td>
   <td>{{user?.email}}</td>
   <td>{{user?.ein}}</td>
   <td><a class="btn btn-clean font-weight-bold btn-sm cursor-pointer" type="button" (click)="editUser(user?.id)">Edit</a></td>
 </tr>

现在这个错误显示来自 HTML 模板行 *ngFor="let user of users

ERROR TypeError: Cannot read properties of null (reading 'users')

at ListUsersComponent_Template (list-users.component.html:68:73)
at executeTemplate (core.mjs:9618:1)
at refreshView (core.mjs:9484:1)
at detectChangesInternal (core.mjs:10837:1)
at ViewRef.detectChanges (core.mjs:21414:1)
at new ListUsersComponent (list-users.component.ts:217:26)
at NodeInjectorFactory.ListUsersComponent_Factory [as factory] (list- users.component.ts:266:4)
at getNodeInjectable (core.mjs:3565:1)
at instantiateAllDirectives (core.mjs:10298:1)
at createDirectivesInstances (core.mjs:9647:1)

我尝试将 trackBydetectChanges() 一起使用,但它显示 用户 null 错误。当页面正在加载并且数据来自我在订阅中绑定的服务时,如何检查我的更改检测。

通过在模型绑定后添加 this.ref.detectChanges(); 并将其从构造函数中删除来解决此问题。

loadUser() {
    const us = this.userService.getUsers('').subscribe(j => {
      this.users = j;
      this.ref.detectChanges(); //added it here after model binding
    });
    this.subscriptions.push(us);
  }

然后用这个 keyvalue documentation and smaller working example ,这是我的 HTML 模板。

<tr align="center" *ngFor="let user of users | keyvalue"> //added this keyvalue
   <td>{{user.value?.id}}</td>
   <td>{{user.value?.userName}} </td>
   <td>{{user.value?.occupation}}</td>
   <td>{{user.value?.companyName}}</td>
   <td>{{user.value?.role}}</td>
   <td>{{user.value?.email}}</td>
   <td>{{user.value?.ein}}</td>
   <td><a class="btn" type="button" (click)="editUser(user.value?.id)">Edit</a></td>
 </tr>