Operaciones de datos remotos de Web Components Grid
De forma predeterminada, IgcGridComponent utiliza su propia lógica para realizar operaciones de datos.
Puede realizar estas tareas de forma remota y alimentar los datos resultantes al IgcGridComponent aprovechando ciertas entradas y eventos, que están expuestos por el IgcGridComponent.
Infinite Scroll
Un diseño popular para escenarios que requieren recuperar datos por fragmentos desde un punto final es el llamado desplazamiento infinito. Para las cuadrículas de datos, se caracteriza por un aumento continuo de los datos cargados provocado por el desplazamiento del usuario final hasta el final. Los siguientes párrafos explican cómo puede utilizar la API disponible para lograr fácilmente un desplazamiento infinito en IgcGridComponent.
Para implementar el desplazamiento infinito, debes recuperar los datos en fragmentos. Los datos que ya se han obtenido deben almacenarse localmente y hay que determinar la longitud de un fragmento y cuántos fragmentos hay. También debe realizar un seguimiento del último índice de fila de datos visible en la cuadrícula. De esta manera, utilizando las propiedades StartIndex y ChunkSize, puede determinar si el usuario se desplaza hacia arriba y debe mostrarle los datos ya obtenidos o si se desplaza hacia abajo y debe obtener más datos desde el punto final.
Lo primero que hay que hacer es obtener el primer fragmento de los datos. Establecer la propiedad es importante, ya que permite que la totalItemCount cuadrícula ajuste el tamaño correcto de su barra de desplazamiento.
Además, debe suscribirse a la salida, de modo que pueda proporcionar los datos que necesita la DataPreLoad cuadrícula cuando intenta mostrar un fragmento diferente, en lugar del cargado actualmente. En el controlador de eventos, debe determinar si desea capturar nuevos datos o devolver datos que ya están almacenados en caché localmente.
import { IgcPropertyEditorPanelModule } from'igniteui-webcomponents-layouts';
import'igniteui-webcomponents-grids/grids/combined';
import { ComponentRenderer, PropertyEditorPanelDescriptionModule, WebGridDescriptionModule } from'igniteui-webcomponents-core';
import { IgcGridComponent, IgcColumnComponent, IgcForOfState } from'igniteui-webcomponents-grids/grids';
import { NwindDataItem, NwindDataItem_LocationsItem, NwindData } from'./NwindData';
import"igniteui-webcomponents-grids/grids/themes/light/bootstrap.css";
import { ModuleManager } from'igniteui-webcomponents-core';
import { RemoteNwindService } from'./NwindService';
ModuleManager.register(
IgcPropertyEditorPanelModule
);
exportclassSample{
private grid: IgcGridComponent;
public remoteData: any;
private page = 1;
private pageSize = 10;
private totalPageCount = 0;
private totalItems = 0;
private iD: IgcColumnComponent
private productName: IgcColumnComponent
private quantityPerUnit: IgcColumnComponent
private unitPrice: IgcColumnComponent
private orderDate: IgcColumnComponent
private discontinued: IgcColumnComponent
private _bind: () =>void;
private remoteService = new RemoteNwindService();
constructor() {
var grid = this.grid = document.getElementById('grid') as IgcGridComponent;
var iD = this.iD = document.getElementById('ID') as IgcColumnComponent;
var productName = this.productName = document.getElementById('ProductName') as IgcColumnComponent;
var quantityPerUnit = this.quantityPerUnit = document.getElementById('QuantityPerUnit') as IgcColumnComponent;
var unitPrice = this.unitPrice = document.getElementById('UnitPrice') as IgcColumnComponent;
var orderDate = this.orderDate = document.getElementById('OrderDate') as IgcColumnComponent;
var discontinued = this.discontinued = document.getElementById('Discontinued') as IgcColumnComponent;
this.grid.isLoading = true;
// load 1 page of data with the size of a data view and a halfconst dataViewSize = 9.6; // grid.height / grid.rowHeight;this.pageSize = Math.floor(dataViewSize * 1.5);
this.remoteService.loadDataForPage(this.page, this.pageSize, (request) => {
if (request.data) {
this.grid.data = this.remoteService.getCachedData({ startIndex: 0, chunkSize: 10 });
this.grid.totalItemCount = this.page * this.pageSize;
this.totalItems = request.data['@odata.count'];
this.totalPageCount = Math.ceil(this.totalItems / this.pageSize);
this.grid.isLoading = false;
}
});
this._bind = () => {
this.grid.addEventListener('dataPreLoad', (e) => {
this.handlePreLoad(e as CustomEvent<IgcForOfState>);
});
}
this._bind();
}
private _nwindData: NwindData = null;
publicgetnwindData(): NwindData {
if (this._nwindData == null) {
this._nwindData = new NwindData();
}
returnthis._nwindData;
}
publichandlePreLoad(e: CustomEvent<IgcForOfState>) {
const isLastChunk = this.grid.totalItemCount === e.detail.startIndex + e.detail.chunkSize;
// when last chunk reached load another page of dataif (isLastChunk) {
if (this.totalPageCount === this.page) {
this.grid.data = this.remoteService.getCachedData(e.detail);
return;
}
this.page++;
this.grid.isLoading = true;
this.remoteService.loadDataForPage(this.page, this.pageSize, (request) => {
if (request.data) {
this.grid.totalItemCount = Math.min(this.page * this.pageSize, this.totalItems);
this.grid.data = this.remoteService.getCachedData(e.detail);
this.grid.isLoading = false;
}
});
} else {
this.grid.data = this.remoteService.getCachedData(e.detail);
}
}
}
new Sample();
ts
<!DOCTYPE html><html><head><title>Sample | Ignite UI | Web Components | infragistics</title><metacharset="UTF-8" /><linkrel="shortcut icon"href="https://static.infragistics.com/xplatform/images/browsers/wc.png" ><linkrel="stylesheet"href="https://fonts.googleapis.com/icon?family=Material+Icons" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Kanit&display=swap" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Titillium Web" /><linkrel="stylesheet"href="https://static.infragistics.com/xplatform/css/samples/shared.v8.css" /><linkrel="stylesheet"href="/src/index.css"type="text/css" /></head><body><divid="root"><divclass="container sample"><divclass="container fill"><igc-gridid="grid"name="grid"height="480px"width="100%"autoGenerate='false'><igc-columnfield="ProductID"></igc-column><igc-columnfield="ProductName"></igc-column><igc-columnfield="UnitPrice"data-type="number"></igc-column><igc-columnfield="UnitsInStock"data-type="number"header-classes="headerAlignSyle"><!-- <ng-template igcHeader>
<span class="cellAlignSyle">UnitsInStock</span>
</ng-template>
<ng-template igcCell let-val>
<div class="currency-badge-container">
<igc-badge *ngIf="val>50" type="success" position="bottom-right" icon="arrow_upward" class="badge-left"></igc-badge>
<igc-badge *ngIf="val<=50" type="error" position="bottom-right" icon="arrow_downward" class="error badge-left"></igc-badge>
<span class="cellAlignSyle" [class.up]="val>50" [class.down]="val<=50">{{ formatNumber(val) }}</span>
</div>
</ng-template> --></igc-column><igc-columnfield="QuantityPerUnit"></igc-column><igc-columnfield="ReorderLevel"data-type="number"header-classes="headerAlignSyle"><!-- <ng-template igcHeader>
<span class="cellAlignSyle">ReorderLevel</span>
</ng-template>
<ng-template igcCell let-val>
<div class="currency-badge-container">
<igc-badge *ngIf="val>20" type="success" position="bottom-right" icon="arrow_upward" class="badge-left"></igc-badge>
<igc-badge *ngIf="val<=20" type="error" position="bottom-right" icon="arrow_downward" class="error badge-left"></igc-badge>
<span class="cellAlignSyle" [class.up]="val>0" [class.down]="val<=0">{{ formatNumber(val) }}</span>
</div>
</ng-template> --></igc-column></igc-grid></div></div></div><!-- This script is needed only for parcel and it will be excluded for webpack -->
<% if (false) { %><scriptsrc="src/index.ts"></script><% } %>
</body></html>html
/* shared styles are loaded from: *//* https://static.infragistics.com/xplatform/css/samples */css
Like this sample? Get access to our complete Ignite UI for Web Components toolkit and start building your own apps in minutes. Download it for free.
Remote Paging
La función de localización puede funcionar con datos remotos. Para demostrar esto, primero declaremos que nuestro servicio será responsable de la obtención de datos. Necesitaremos el recuento de todos los elementos de datos para poder calcular el recuento de páginas. Esta lógica se agregará a nuestro servicio.
exportclassRemotePagingService{
publicstatic CUSTOMERS_URL = `https://data-northwind.indigo.design/Customers/GetCustomersWithPage`;
constructor() {}
publicstaticgetDataWithPaging(pageIndex?: number, pageSize?: number) {
return fetch(RemotePagingService.buildUrl(RemotePagingService.CUSTOMERS_URL, pageIndex, pageSize))
.then((result) => result.json())
.catch((error) =>console.error(error.message));
}
privatestaticbuildUrl(baseUrl: string, pageIndex?: number, pageSize?: number) {
let qS = "";
if (baseUrl) {
qS += `${baseUrl}`;
}
// Add pageIndex and size to the query string if they are definedif (pageIndex !== undefined) {
qS += `?pageIndex=${pageIndex}`;
if (pageSize !== undefined) {
qS += `&size=${pageSize}`;
}
} elseif (pageSize !== undefined) {
qS += `?perPage=${pageSize}`;
}
return`${qS}`;
}
}
ts
Después de declarar el servicio, debemos crear un componente, que será responsable de la construcción y la IgcGridComponent suscripción de datos.
Primero tenemos que enlazar a los eventos relevantes para que cuando cambiemos las páginas y la cantidad de registros que se muestran por página, el servicio remoto obtenga la cantidad correcta de datos
<!DOCTYPE html><html><head><title>Sample | Ignite UI | Web Components | infragistics</title><metacharset="UTF-8" /><linkrel="shortcut icon"href="https://static.infragistics.com/xplatform/images/browsers/wc.png" ><linkrel="stylesheet"href="https://fonts.googleapis.com/icon?family=Material+Icons" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Kanit&display=swap" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Titillium Web" /><linkrel="stylesheet"href="https://static.infragistics.com/xplatform/css/samples/shared.v8.css" /><linkrel="stylesheet"href="/src/index.css"type="text/css" /></head><body><divid="root"><divclass="container sample ig-typography"><divclass="container fill"><igc-gridauto-generate="false"name="grid"id="grid"moving="true"paging-mode="Remote"><igc-paginatorid="paginator"></igc-paginator><igc-columnname="customerId"id="customerId"field="customerId"hidden="true"></igc-column><igc-columnname="companyName"id="companyName"field="companyName"header="Company Name"></igc-column><igc-columnname="contactName"id="contactName"field="contactName"header="Contact Name"></igc-column><igc-columnname="contactTitle"id="contactTitle"field="contactTitle"header="Contact Title"></igc-column><igc-columnname="address?.country"id="address.country"field="address.country"header="Country"></igc-column><igc-columnname="address.phone"id="address.phone"field="address.phone"header="Phone"></igc-column></igc-grid></div></div></div><!-- This script is needed only for parcel and it will be excluded for webpack -->
<% if (false) { %><scriptsrc="src/index.ts"></script><% } %>
</body></html>html
/* shared styles are loaded from: *//* https://static.infragistics.com/xplatform/css/samples */css
Known Issues and Limitations
Cuando la grilla no tiene PrimaryKey configurada y los escenarios de datos remotos están habilitados (al paginar, ordenar, filtrar y desplazar solicitudes de activación a un servidor remoto para recuperar los datos que se mostrarán en la grilla), una fila perderá el siguiente estado después de un dato. solicitud completa: