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

Angular Mat-Accordion动态加载无显示问题求助

问题排查与修复方案

我一眼就发现了问题的核心——你的组件完全没有把服务返回的数据赋值给costCategories变量,另外还有两处语法细节错误,这就是页面空白且无报错的原因!

核心问题拆解

  1. 数据未赋值:在subscribe的成功回调里,你只更新了isLoading状态,却漏掉了把接口返回的costCategories赋值给组件类的同名变量,导致模板里的*ngFor遍历的是undefined,自然渲染不出任何内容。
  2. 错误回调写法错误:你把错误处理逻辑嵌套在了成功回调函数内部,这会导致错误永远不会被触发,正确的做法是把它作为subscribe的第二个独立参数。
  3. 语法小疏漏:isLoading = true后面缺少分号,虽然编译器可能容错,但规范写法需要补上。

修正后的TypeScript代码

@Component({ 
  selector: 'cost-categories', 
  templateUrl: './cost-categories.component.html', 
  styleUrls: ['./cost-categories.component.scss'], 
})
export class CostCategoriesComponent implements OnInit { 
  panelOpenState = false; 
  costCategories: ICostCategories[] = []; // 建议初始化空数组,避免undefined引发潜在问题
  isLoading = true; // 补上缺失的分号

  constructor(public wellService: WellsService) { } 

  ngOnInit() { 
    this.wellService.getCostCategories().subscribe(
      // 成功回调:给组件变量赋值+更新加载状态
      (costCategories: ICostCategories[]) => { 
        this.costCategories = costCategories; // 这是关键!必须赋值才能让模板拿到数据
        this.isLoading = false; 
      },
      // 错误回调:作为subscribe的第二个独立参数
      (err: WellError) => console.log(err.friendlyMessage) 
    ); 
  }
}

优化后的模板代码(可选,增加加载提示)

为了提升用户体验,建议在数据加载过程中显示加载状态:

<mat-accordion *ngIf="!isLoading; else loadingTemplate"> 
  <mat-expansion-panel *ngFor="let item of costCategories"> 
    <mat-expansion-panel-header> 
      {{item.wellName}} 
    </mat-expansion-panel-header> 
    Description here 
  </mat-expansion-panel> 
</mat-accordion>

<ng-template #loadingTemplate>
  <p>数据加载中...</p> <!-- 也可以替换成Angular Material的进度条组件 -->
</ng-template>

额外最佳实践建议

  • 给costCategories初始化空数组,能避免数据未返回时*ngFor遍历undefined的潜在问题。
  • 可以考虑使用async管道简化订阅逻辑(比如*ngFor="let item of costCategories$ | async"),无需手动管理订阅生命周期,更符合Angular的设计理念。

内容的提问来源于stack exchange,提问作者Farzzy - MSFT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 20:17:36