Ag-Grid Angular无限滚动模式下多参数HTTP Get请求实现问询
Hey there! Let's break down how to set up that parameterized GET request for your Ag-Grid Infinity Scrolling setup, using JSONPlaceholder as your mock backend. I'll walk you through each step and integrate it with your existing onGridReady code.
Step 1: Configure Ag-Grid for Infinity Scrolling
First, make sure your Ag-Grid component has the right properties enabled to use infinite scrolling and server-side sorting. Here's how your template might look:
<ag-grid-angular [rowModelType]="'infinite'" [cacheBlockSize]="50" <!-- Matches your example's end=50 (loads 50 rows at a time) --> [serverSideSorting]="true" <!-- Enables passing sort parameters to your API --> [columnDefs]="columnDefs" (gridReady)="onGridReady($event)" ></ag-grid-angular>
In your component class, define your column definitions (make sure the sortable field matches your example's Number column):
columnDefs = [ { field: 'Number', sortable: true }, // This will trigger sort model updates // Add other columns you need here ];
Step 2: Implement the getRows Data Source Method
The core of infinite scrolling is the getRows function, which Ag-Grid calls whenever it needs more data. This is where you'll build your parameterized GET request. Let's integrate it with your existing onGridReady code:
onGridReady(params) { params.api.sizeColumnsToFit(); // Set up the infinite scroll datasource params.api.setDatasource({ getRows: this.getRows.bind(this) // Bind `this` to access component properties }); } getRows(params) { // 1. Extract parameters from Ag-Grid's request const page = Math.floor(params.startRow / params.endRow) + 1; // Calculate page number (0-50 = page 1) const start = params.startRow; const end = params.endRow; // 2. Process sort parameters into URL-encoded JSON let sortParam = ''; if (params.sortModel.length > 0) { // Convert Ag-Grid's sort model to JSON, then encode it for the URL const sortJson = JSON.stringify(params.sortModel); sortParam = encodeURIComponent(sortJson); } // 3. Build the request URL with all parameters const baseUrl = 'https://jsonplaceholder.typicode.com/posts'; // Mock backend endpoint const requestUrl = new URL(baseUrl); // Add all required parameters requestUrl.searchParams.append('_dc', Date.now().toString()); // Cache-busting timestamp requestUrl.searchParams.append('page', page.toString()); requestUrl.searchParams.append('start', start.toString()); requestUrl.searchParams.append('end', end.toString()); if (sortParam) { requestUrl.searchParams.append('sort', sortParam); } // 4. Send the GET request and feed data back to Ag-Grid fetch(requestUrl.toString()) .then(response => response.json()) .then(data => { // Since JSONPlaceholder doesn't return total row count, we'll mock it (adjust as needed) const totalMockRows = 100; // Tell Ag-Grid we've successfully loaded data params.successCallback(data, totalMockRows); }) .catch(error => { console.error('Failed to fetch data:', error); // Notify Ag-Grid of the error params.failCallback(); }); }
Key Details to Note:
- Parameter Calculation: The
pageparameter is derived fromstartRowandendRowto match your example's pagination logic. - Sort Parameter Handling: Ag-Grid's
sortModelis an array of objects (like[{property: 'Number', direction: 'DESC'}]), which we convert to JSON and URL-encode to match your example's format. - URL Safety: Using
URLandURLSearchParamsautomatically handles proper encoding of parameters, avoiding issues with special characters. - Mock Backend Adjustment: JSONPlaceholder doesn't support all the parameters you're using (like
start/end), but this setup will send the correct request structure—you can swap out thebaseUrlfor your real API once ready.
内容的提问来源于stack exchange,提问作者Mia

