使用Mat-paginator和Mat-option

时间:2020-07-01 11:16:31

标签: html angular angular-material observable

我正在使用角度材料和可观察对象来创建带有mat-paginatormat-option的异步列表(而不是使用表,而是根据客户要求)。我想用HTML进行分页,但要使用可观察的流,而不要使用分页和对分页的辅助数组的赋值。

示例:

<mat-option *ngFor="let elem of opMvAsync | async">
    <!-- Data printed here -->
</mat-option>
<mat-paginator *ngIf="(opMvAsync | async)?.length > 5" [length]="(opMvAsync | async)?.length" [hidePageSize]="true" [pageSize]="5" (page)="onPageChange($event)"></mat-paginator>

还有TS:

//TS 
  opMvAsync : Observable<Array<Items>>;

ngOnInit() {
  this.opMvAsync = this.service.getItems();
}

我的应用程序中还有另一个示例,非常相似,但是使用了辅助数组:

<!-- HTML-->
<mat-option *ngFor="let elem of lstPaginated">
    <!-- Data printed here -->
</mat-option>
<mat-paginator *ngIf="lstOri.length > 5" [length]="lstOri.length" [hidePageSize]="true" [pageSize]="5" (page)="onPageChange($event)"></mat-paginator>

// TS
lstOri: Array<Items>;
lstPaginated: Array<Items>;

ngOnInit() {
  this.service.getItems().subscribe(r=> {
      this.lstOri= r;
      this.lstPaginated= this.lstOri.slice(0, 5);
  });
}
onPageChange(event: PageEvent) {
    this.lstPaginated= this.lstOri.slice(event.pageIndex * event.pageSize, event.pageIndex * event.pageSize + event.pageSize);
    }

这很好用,但是必须不断处理两个数组非常费力。

有什么方法可以直接对可观察对象进行分页吗?感谢您的进步。

编辑:我需要弄清楚我用HTML呈现的可观察物的分页方式。我的OnPageChange应该处理显示的可观察元素,但是我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

您可以按照以下模式解决此问题。

  1. 在您的service中,而不是使用方法getItems(),而是创建一个变量items$。并将其值设置为get / post方法调用。
  2. 在组件中,将opMvAsync设置为等于service.items$
  3. 现在在您的模板中,将其与async管道一起使用。

下面是示例代码:

my.service.ts

@Injectable({  providedIn: 'root', })
export class MyService {
  ...
  items$ = this.http.get('some/url/').pipe(...);
  ...
}

app.component.ts

export class AppComponent {
 ...
 public opMvAsync$ = this.service.items$.pipe(...);
 ...
}

app.component.html

<div *ngIf="opMvAsync$ | async as opMvAsync">
  <mat-option *ngFor="let elem of opMvAsync | async">
  <!-- Data printed here -->
  </mat-option>
</div>

通过这种方式,您可以避免订阅/取消订阅的工作,因为async关键字可以解决此问题。