如何通过Django REST Framework API在ng2-smart-table下拉框展示数据
How to Populate ng2-smart-table Dropdown via Django REST Framework API
Got it, let's fix this step by step. Your current code has a hardcoded (and incorrect) list for the dropdown—we need to fetch data from your DRF API first, then feed it into ng2-smart-table's editor config. Here's the complete solution:
Step 1: Update Your Service (Optional but Recommended)
If you're using Angular 4.3+, the old Http module is deprecated. Switch to HttpClient which handles JSON parsing automatically, so you don't need .map(response => response.json()):
// service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class ProductService { constructor(private http: HttpClient) {} get_type(): Observable<any[]> { return this.http.get<any[]>('http://127.0.0.1:8000/productype/') .pipe( catchError(error => { console.error('Failed to load product types:', error); return throwError(() => new Error(error.statusText)); }) ); } }
Step 2: Fetch Data & Configure Table in Your Component
We'll fetch the product types when the component initializes, transform the data into the format ng2-smart-table expects, then set up the table settings dynamically.
// component.ts import { Component, OnInit } from '@angular/core'; import { ProductService } from './product.service'; @Component({ selector: 'app-product-table', templateUrl: './product-table.component.html' }) export class ProductTableComponent implements OnInit { settings: any; productTypes: { title: string, value: any }[] = []; // Stores dropdown options constructor(private productService: ProductService) {} ngOnInit(): void { // Fetch product types from API first this.productService.get_type().subscribe({ next: (types) => { // Transform DRF response to ng2-smart-table's required format // Adjust `type.name` and `type.id` to match your DRF model fields this.productTypes = types.map(type => ({ title: type.name, // Text shown in dropdown value: type.id // Value saved when selected (can use entire object if needed) })); // Initialize table settings now that we have data this.initTableSettings(); }, error: (err) => console.error('Error loading product types:', err) }); } private initTableSettings(): void { this.settings = { // Add your other table settings here (mode, actions, etc.) columns: { ptype: { title: 'Product Type', type: 'string', width: '50%', editor: { type: 'list', config: { list: this.productTypes, // Use the fetched options here } }, // Optional: Show the dropdown title instead of raw value in the table valuePrepareFunction: (cellValue) => { const matchingType = this.productTypes.find(type => type.value === cellValue); return matchingType ? matchingType.title : 'Unknown Type'; } }, // Add your other columns here } }; } }
Key Notes:
- Wait for API Data: We initialize the table settings after the API call succeeds—this ensures the dropdown list isn't empty when the table loads.
- Data Format: ng2-smart-table's list editor requires options in
{ title: string, value: any }format. Adjusttype.nameandtype.idto match the actual fields returned by your DRF endpoint (e.g., if your model useslabelinstead ofname, update that). - Value Display: The
valuePrepareFunctionconverts the saved value (like an ID) back to a human-readable title in the table cells. - Error Handling: Always add error handling to catch API failures so you can debug issues easily.
内容的提问来源于stack exchange,提问作者hari prasanth
相关产品推荐
相关产品推荐

