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

Angular Cli中为按钮添加加载Spinner:请求完成前显示加载状态

嘿,我来帮你搞定Angular里的加载状态显示!其实思路很简单——用一个布尔变量来控制加载提示的显示和隐藏,配合HTTP请求的生命周期来切换状态就行。下面是具体的实现步骤:

第一步:在组件类中添加加载状态逻辑

首先在quotes.component.ts里新增一个isLoading变量,用来标记当前是否处于加载状态。然后修改onGetQuotes方法,在发起请求前把isLoading设为true,请求完成(不管成功还是失败)后再设回false:

import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
// 假设你已经导入了用于获取数据的服务,比如QuoteService

@Component({
  selector: 'app-quotes',
  templateUrl: './quotes.component.html',
  styleUrls: ['./quotes.component.css']
})
export class QuotesComponent implements OnInit {
  quotes: any[] = [];
  isLoading = false; // 新增加载状态标记

  constructor(private quoteService: QuoteService) { }

  ngOnInit(): void {
  }

  onGetQuotes() {
    this.isLoading = true; // 发起请求前开启加载状态
    this.quoteService.getQuotes()
      .subscribe(
        (response: Response) => {
          this.quotes = response.json();
          this.isLoading = false; // 请求成功后关闭加载状态
        },
        (error) => {
          console.error('获取数据失败:', error);
          this.isLoading = false; // 即使请求失败,也要关闭加载状态,避免一直显示加载
        }
      );
  }

  onDelete(event: any) {
    // 你的删除逻辑保持不变
  }
}

第二步:在模板中添加加载提示的UI

接下来修改quotes.component.html,用*ngIf指令根据isLoading的值来显示加载提示(spinner或文本),同时控制数据列表的显示时机:

<div class="btn btn-primary" (click)="onGetQuotes()">Get Quotes</div>
<hr>

<!-- 加载状态提示:加载中时显示 -->
<div *ngIf="isLoading" class="text-center my-4">
  <!-- 这里用Bootstrap的spinner组件,如果你没用到Bootstrap,换成普通文本也可以 -->
  <div class="spinner-border text-primary" role="status">
    <span class="visually-hidden">加载中...</span>
  </div>
  <p class="mt-2">请等待...</p>
</div>

<!-- 数据列表:加载完成且有数据时显示 -->
<app-quote 
  *ngIf="!isLoading && quotes.length > 0"
  *ngFor="let quote of quotes" 
  [quote]="quote" 
  (quoteDelete)="onDelete($event)"
></app-quote>

<!-- 空状态提示:加载完成但无数据时显示 -->
<div *ngIf="!isLoading && quotes.length === 0" class="text-center my-4">
  暂无数据,请点击「Get Quotes」获取
</div>

额外小提示

  • 如果你不想用Bootstrap的spinner,可以直接替换成纯文本,比如<p>正在获取数据,请稍候...</p>,或者自己写CSS动画实现加载效果。
  • 一定要在请求的error回调里也设置isLoading = false,不然如果请求失败,用户会一直看到加载提示,体验很差。
  • 可以给加载提示加一些样式,比如居中、上下margin,让页面布局更协调。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:01:22