如何使用Angular 8在資料從API載入期間顯示載入動畫(Spinner)?


本文將學習如何在Angular 8中使用HTTPClient服務從模擬的todos API獲取資料,並在資料載入期間在螢幕上顯示載入動畫。

Angular 8是一個構建Web應用程式的強大框架。它提供了許多功能,使建立動態且互動式的使用者介面變得容易。

讓我們使用該框架並透過一個示例瞭解如何有條件地顯示載入動畫元件。

前提條件

在繼續以下步驟之前,請確保您的系統上已安裝Angular CLI,因為我們在後續過程中將大量依賴它。

步驟 1

首先,我們將建立一個Angular應用程式,併為其命名。在本例中,我們將使用名稱“my-app”。

ng new my-app
cd my-app

步驟 2

讓我們建立一個新的元件來顯示載入動畫。使用以下命令生成一個新元件,並在“src/app”資料夾內建立一個名為“spinner”的新資料夾

ng generate component spinner

步驟 3

開啟“spinner.component.html”檔案並新增以下程式碼 -

<div class="spinner">

此程式碼將為我們需要的載入動畫新增必要的HTML到DOM。

步驟 4

接下來,開啟“spinner.component.css”檔案並新增以下程式碼 -

.spinner {
   width: 40px;
   height: 40px;
   border-radius: 50%;
   border-top: 3px solid #3498db;
   border-right: 3px solid transparent;
   animation: spin 1s linear infinite;
}
@keyframes spin {
   to {
      transform: rotate(360deg);
   }
}

這將建立一個載入動畫,我們將在從伺服器獲取資料時顯示它。

步驟 5

現在讓我們使用此元件在等待從API載入資料時顯示載入動畫。開啟“app.component.ts”檔案並新增以下程式碼 -

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
   data: any;
   loading?: boolean;

   constructor(private http: HttpClient) { }

   async ngOnInit() {
      this.loading = true;
      await new Promise(resolve => setTimeout(resolve, 2000));
      this.http.get('https://jsonplaceholder.typicode.com/todos/1').subscribe(response => {
         this.data = response;
         this.loading = false;
      });
   }
}

步驟 6

現在在您的應用程式模組中匯入HttpClientModule。開啟app.module.ts檔案並貼上以下程式碼 -

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SpinnerComponent } from './spinner/spinner.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
   declarations: [
      AppComponent,
      SpinnerComponent
   ],
   imports: [
      BrowserModule,
      AppRoutingModule,
      HttpClientModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }

步驟 7

最後,開啟“app.component.html”檔案並新增以下程式碼 -

<div class="container">
   <div *ngIf="loading" class="spinner-container">
      <app-spinner></app-spinner>
   </div>
   <div *ngIf="!loading">
      <pre>{{ data | json }}</pre>
   </div>
</div>

結論

在本文中,我們學習瞭如何建立一個Angular 8應用程式,該應用程式在等待從API載入資料時在螢幕上顯示載入動畫。我們瞭解瞭如何使用HttpClient服務從API獲取資料並在螢幕上顯示它。我們還了解了如何使用CSS建立一個簡單的載入動畫,並在等待資料載入時顯示它。

更新於: 2023年8月3日

686 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.