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

页面加载过慢,如何添加Loading Gif并按指定时长显示?

实现加载动画(Loading Gif)的方案

步骤1:在组件类中添加加载状态变量

在myvalues.component.ts里声明一个控制加载状态的变量:

isLoading: boolean = true;

步骤2:修改数据获取方法,保证加载时长至少2秒

更新getHomeValuesList方法,同时处理API请求和固定2秒延迟,取两者中耗时更长的作为加载时长:

async getHomeValuesList() {
  this.isLoading = true;
  const request: HomeValuesRequest = {
    userId: this.currentUser.userId,
    userName: this.currentUser.userName
  };

  // 并行执行API请求和2秒延迟,确保加载至少显示2秒
  const [result] = await Promise.all([
    this.ValuesMatchingService.homeValuesList(request),
    new Promise(resolve => setTimeout(resolve, 2000))
  ]);

  const response = result.data;
  // 排序数据
  const descedingValues = response.ValuesModels.sort((a, b) => {
    const dateA = new Date(a.valuesDate).getTime();
    const dateB = new Date(b.valuesDate).getTime();
    return dateA < dateB ? 1 : -1;
  });

  // 格式化金额并赋值(用map替代forEach+push,更高效)
  this.values = descedingValues.map(data => ({
    ...data,
    amountStr: data.amount.toLocaleString()
  }));

  this.isLoading = false;
}

步骤3:在HTML中添加Loading Gif和控制显示逻辑

修改HTML代码,添加加载动画容器,并用*ngIf控制加载动画和表格的显示切换:

<!-- 加载动画容器 -->
<div *ngIf="isLoading" class="loading-container">
  <img src="/assets/loading.gif" alt="加载中..." /> <!-- 替换为你的Gif路径 -->
</div>

<!-- 表格仅在加载完成后显示 -->
<table *ngIf="!isLoading">
  <thead>
    <tr>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let value of values">
      <td>{{value.id}}</td> <!-- 修正原代码的标签闭合错误 -->
    </tr>
  </tbody>
</table>

步骤4:添加加载动画的样式(可选)

在组件的CSS文件中添加样式,让加载动画居中显示:

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

说明

  • 如果API请求耗时超过2秒,加载动画会持续到请求完成;如果请求耗时不足2秒,动画会显示满2秒再隐藏,完全符合需求。
  • 修正了原HTML中<td/>的标签闭合错误,避免渲染问题。
  • 使用map替代forEach+push优化数据处理逻辑,代码更简洁高效。

内容的提问来源于stack exchange,提问作者Celal Sunnetci

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:39:40