加载页面时数组为[]

时间:2019-01-16 11:54:47

标签: angular-material angular-cli

即使我在ngOnInit()方法中调用API,我也试图找出数组为何为[],但是如果我按页面上的下一页按钮,则数组不再等于[]。 对我来说奇怪的是,如果我使用

*ngFor="let item of users"

它将显示,没有问题。

TS文件:

export class DisplayAccountsComponent implements OnInit {
  // MatPaginator INPUT
  length: number;
  pageSize = 1;
  pageSizeOptions: number[] = [1, 5, 10 , 25, 50];

  users: User[] = [];
  activePageDataChunk = [];

  constructor(private _displayAccountService: DisplayAccountsService) {
  }

  ngOnInit() {
    this.getAllUsers();
    this.activePageDataChunk = this.users.slice(0, this.pageSize);
    console.log(this.users);
    console.log(this.activePageDataChunk);
  }

  onPageChanged(e) {
    const firstCut = e.pageIndex * e.pageSize;
    const secondCut = firstCut + e.pageSize;
    this.activePageDataChunk = this.users.slice(firstCut, secondCut);
    console.log(this.activePageDataChunk);
  }

  getAllUsers() {
    this._displayAccountService.getAllUsers().subscribe(
      data => {
        this.users = data;
        this.length = this.users.length;
      },
      err => {
        console.log(err);
      }
    );
  }

还有HTML文件:

<div *ngFor="let user of activePageDataChunk">
   <p>{{user.firstName}} | {{user.lastName}} | {{user.email}}</p> 
</div> 
<mat-paginator [length]="length" [pageSize]="pageSize"
[pageSizeOptions]="pageSizeOptions" (page)="onPageChanged($event)">
</mat-paginator>

正如我所说,当页面加载用户时,activePageDataChunk等于[],但是如果按下一页,变量将不再等于[]。 预先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

getAllUsers()发出异步请求。行this.activePageDataChunk = this.users.slice(0, this.pageSize);将在异步请求完成之前执行,因此this.usersthis.activePageDataChunk将为空数组。请求完成后,它将用数据填充this.users,并且在单击下一页按钮时,此行this.activePageDataChunk = this.users.slice(firstCut, secondCut);将首次用数据填充activePageDataChunk,因此您将能够看到点击下一页的数据。

要解决此问题,您可以将代码更改为以下内容:

ngOnInit() {
  this._displayAccountService.getAllUsers().subscribe(
    data => {
      this.users = data;
      this.length = this.users.length;
      this.activePageDataChunk = this.users.slice(0, this.pageSize);
    },
    err => {
      console.log(err);
    }
  );
}