雖然 Angular 有自己的非同步方法 .subscribe(),但我還是習慣使用 Async / Await 和 try / catch / finally,比較有安全感。
本篇分享自己使用 Async / Await 的方式,大家可以參考看看唷!
import { Component, signal, inject, OnInit } from '@angular/core';
import { firstValueFrom } from 'rxjs';
@Component({})
export default class Product implements OnInit {
private readonly apiService = inject(ApiService);
private readonly storageService = inject(StorageService);
readonly isFinished = signal(false);
ngOnInit(): void {
this.getProductList();
}
/**
* 取得全部的產品資訊
*/
private async getProductList(): Promise<void> {
this.isFinished.set(true);
try {
let res = await firstValueFrom(this.apiService.getProductList());
this.storageService.store('PRODUCT_LIST', res, 'SESSION');
} catch (error) {
alertService.toastError(`無法取得資料,請稍後再試。`);
} finally {
this.isFinished.set(false);
}
}
}
firstValueFrom:因為 getCareerList() 回傳的是 Observable (Angular HttpClient),必須使用呼叫 firstValueFrom 或 lastValueFrom 將 Observable 轉為 Promise 後再 await。
如果 getCareerList() 本身已經在 Service 內部被封裝成 Promise,便不需要這一層轉換。
// 使用 firstValueFrom 訂閱並取第一個 emitted 數值轉為 Promise
const res = await firstValueFrom(this.apiService.getCareerList());
想要知道更多關於 Angular 非同步的技巧,
歡迎瀏覽我的好朋友—前端大師安東尼的鐵人賽文章:
Day 16:即將登場的 Route Resources,Angular Router 為什麼需要新的資料載入方式?