Angular中HTTP POST提交数据后,如何通过*ngFor在组件中展示服务端返回数据
Hey there! Let's fix this step by step. I see a few small issues in your code that are keeping you from displaying the data correctly. Here's what you need to adjust:
1. Fix the API Service Response Type
Your current service sets responseType: 'text', but the server is returning JSON data. This means you're getting a raw string instead of a parsed object. Let's update the service to handle JSON properly (and add type safety while we're at it):
// service.ts searchByCompanyId(companyId){ // Remove {responseType: 'text'} (default is JSON) and add type casting return this.http.post<Fin>(environment.appApiUrl + '/api/url', companyId); }
2. Update Component Logic to Handle the Single Object
The server returns a single Fin object, not an array, but your component has finData: Fin[] = [] (an array). You have two straightforward options here:
Option A: Keep using an array (good if you might show multiple entries later)
Update your submit() method to replace or add the response to the array:
// component.ts submit() { this.apiService.searchByCompanyId(this.finForm.get('companyId')?.value).subscribe( (response: Fin) => { // Convert id from string to number to match your model response.id = Number(response.id); // Clear previous data and add the new entry this.finData = [response]; // Use this.finData.push(response); if you want to retain old entries }, (error) => { // Don't skip error handling! console.error('Failed to fetch data:', error); } ); }
Note: I changed this.finForm.value to this.finForm.get('companyId')?.value because your server likely expects just the ID number, not the full form object. Adjust this if your server expects the entire object.
Option B: Use a single object (simpler for single-entry display)
Change finData to hold a single object instead of an array:
// component.ts finData: Fin | undefined; // Single object, not array submit() { this.apiService.searchByCompanyId(this.finForm.get('companyId')?.value).subscribe( (response: Fin) => { response.id = Number(response.id); this.finData = response; }, (error) => { console.error('Failed to fetch data:', error); } ); }
3. Update the Template to Display Data
If you chose Option A (array):
Your existing *ngFor will work, but add checks for empty states:
<div *ngIf="finData.length > 0"> <div *ngFor="let item of finData"> <p>Name: {{item.name}}</p> <p>ID: {{item.id}}</p> <p>District: {{item.district}}</p> <p>City: {{item.city}}</p> </div> </div> <div *ngIf="finData.length === 0 && finForm.get('companyId')?.value"> No data found for the entered ID. </div>
If you chose Option B (single object):
Remove the *ngFor and use *ngIf to avoid null errors:
<div *ngIf="finData"> <p>Name: {{finData.name}}</p> <p>ID: {{finData.id}}</p> <p>District: {{finData.district}}</p> <p>City: {{finData.city}}</p> </div> <div *ngIf="!finData && finForm.get('companyId')?.value"> No data found for the entered ID. </div>
That should get your data showing up as expected! Let me know if you hit any snags along the way.
内容的提问来源于stack exchange,提问作者BeauNut

