You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Angular:传递Select的company_id参数至API获取对应数据求助

Got it, let's fix this step by step. The main issues here are that your current code only fetches data once on component initialization, and doesn't react to changes in the company dropdown selection. Here's how to make it work:

Step 1: Add a change handler to the company dropdown

First, update your company select in home.html to trigger a method whenever the selection changes. We'll use (ngModelChange) for this:

<select class="form-control" [(ngModel)]="userFilter.company_id" (ngModelChange)="fetchClaimsByCompany()">
  <option value='' >All</option>
  <option value="999">Airlink Communication</option>
  <option value="637">Ascertia (Pvt) Ltd</option>
  <option value="1053">Frontier Works Organization</option>
  <option value="1174">Ebryx (pvt) Ltd</option>
  <option value="274">HY Enterprises (Pvt) Limited</option>
  <option value="459">Naimat Saleem trust NST (US GROUP)</option>
  <option value="659">Samad Rubber Works (Pvt) Ltd</option>
  <option value="56">Sundry Clients</option>
  <option value="620">TIMEXPERTS (PRIVATE) Limited</option>
  <option value="39">US Apparel &amp; Textile (Pvt) Limited</option>
  <option value="40">US Denim Mills (Pvt) Limited</option>
</select>

Step 2: Refactor the API call to accept dynamic company_id

Modify your home.component.ts to make the API request dynamic, include the company_id parameter when selected, and add proper subscription cleanup to avoid memory leaks:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ApiService } from 'app/services/api/api.service';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit, OnDestroy {
  data: any = [];
  userFilter: any = { claim_no:'', member_name:'', status:'', company_id: ''};
  // Track API subscription to clean up later
  private claimsSubscription: Subscription | undefined;
  // Map company IDs to names for cleaner template rendering
  companyMap: Record<string, string> = {
    '999': 'Airlink Communication',
    '637': 'Ascertia (Pvt) Ltd',
    '1053': 'Frontier Works Organization',
    '1174': 'Ebryx (pvt) Ltd',
    '274': 'HY Enterprises (Pvt) Limited',
    '459': 'Naimat Saleem trust NST (US GROUP)',
    '659': 'Samad Rubber Works (Pvt) Ltd',
    '56': 'Sundry Clients',
    '620': 'TIMEXPERTS (PRIVATE) Limited',
    '39': 'US Apparel & Textile (Pvt) Limited',
    '40': 'US Denim Mills (Pvt) Limited'
  };

  constructor(private api: ApiService, public httpClient: HttpClient) {}

  ngOnInit(): void {
    // Fetch initial data (all companies) when component loads
    this.fetchClaimsByCompany();
  }

  ngOnDestroy(): void {
    // Clean up subscription to prevent memory leaks
    if (this.claimsSubscription) {
      this.claimsSubscription.unsubscribe();
    }
  }

  fetchClaimsByCompany(): void {
    // Build API URL with company_id parameter if a company is selected
    let apiUrl = 'xyz.com'; // Replace with your actual API base URL
    if (this.userFilter.company_id) {
      apiUrl += `?company_id=${this.userFilter.company_id}`;
    }

    // Cancel any ongoing API request before making a new one
    if (this.claimsSubscription) {
      this.claimsSubscription.unsubscribe();
    }

    // Make the API request
    this.claimsSubscription = this.httpClient.get(apiUrl)
      .subscribe({
        next: (response: any) => {
          console.log('Fetched claims:', response);
          this.data = response.records;
        },
        error: (err) => {
          console.error('Error fetching claims:', err);
          // Add user-friendly error handling here (e.g., toast notification)
        }
      });
  }
}

Step 3: Clean up company name display in the template

Instead of using multiple *ngIf statements for company names, use the companyMap we created to simplify the table cell:

<td>{{ companyMap[x.company_id] || 'Unknown Company' }}</td>

Optional: Support combined filters

If you want the API to respect all your filters (name, claim number, status, company), build a full query string instead of just the company_id:

fetchClaimsByCompany(): void {
  const params = new URLSearchParams();
  if (this.userFilter.company_id) params.append('company_id', this.userFilter.company_id);
  if (this.userFilter.member_name) params.append('member_name', this.userFilter.member_name);
  if (this.userFilter.claim_no) params.append('claim_no', this.userFilter.claim_no);
  if (this.userFilter.status) params.append('status', this.userFilter.status);

  const apiUrl = `xyz.com?${params.toString()}`;

  // Rest of the subscription code remains the same...
}

Key Improvements:

  • Dynamic API Calls: The app now fetches fresh data whenever the company selection changes.
  • Subscription Cleanup: Prevents memory leaks by unsubscribing from API calls when the component is destroyed.
  • Cleaner Template: The companyMap eliminates repetitive *ngIf checks and makes future company updates easier.
  • Error Handling: Basic error logging is added – expand this with user-facing messages for better UX.

内容的提问来源于stack exchange,提问作者Umaiz Khan

火山引擎 最新活动