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

从Service层获取到数据但HTML页面无法显示的技术咨询

It looks like you're running into a common Angular issue where async data isn't rendering in the template. Let's break down the possible fixes based on your code:

1. First, confirm data is actually being fetched

Add a console log in your subscribe callback to make sure the API is returning data. If you don't see the log or get an error, the problem is with the API call itself, not the template:

this.service.get_bussiness().subscribe(
  users => {
    console.log('Fetched users:', users); // Check this in dev tools
    this.users = users;
  },
  error => console.error('API Error:', error)
);

2. Initialize the users array to avoid undefined errors

Right now, users is declared but not initialized. When the template loads before the API response comes in, it might try to iterate over undefined which can cause silent failures. Initialize it as an empty array:

export class NewExpenseComponent { 
  users: any[] = []; // Initialize here
  // ... rest of your code
}

3. Check your template syntax

Make sure you're correctly looping over the users array in your HTML. For example, if each user has a name property, your template should look like this:

<div *ngFor="let user of users">
  {{ user.name }} <!-- Replace with actual properties from your API -->
</div>

4. Use the Async Pipe (Cleaner Approach)

Instead of manually subscribing in the component, you can use Angular's async pipe to handle subscriptions and change detection automatically. This avoids potential memory leaks and simplifies your code:

Component.ts:

export class NewExpenseComponent { 
  users$: Observable<any[]>; // Declare as observable
  toastConfig: ToasterConfig; 

  constructor(private service: ExpensesService, /* other injectables */) { 
    this.users$ = this.service.get_bussiness(); // Assign the observable directly
  } 
}

Template:

<div *ngFor="let user of users$ | async">
  {{ user.name }}
</div>

5. Verify API Response Structure

Sometimes APIs wrap the array in an object (e.g., { "data": [...] }). If that's the case, you need to extract the array from the response:

this.service.get_bussiness().subscribe(
  response => this.users = response.data, // Adjust 'data' to match your API's key
  error => console.error(error)
);

Try these steps one by one, starting with confirming the data is being fetched. That should help you pinpoint why the data isn't showing up in your HTML.

内容的提问来源于stack exchange,提问作者Sudharsan Venkatraj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:59:33