You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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:

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. Adjust type.name and type.id to match the actual fields returned by your DRF endpoint (e.g., if your model uses label instead of name, update that).
  • Value Display: The valuePrepareFunction converts 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:58:58