進入正題前,先來複習什麼是「同步」、「非同步」。
const a = 2;
const b = 3;
let total = a + b;
console.log(total);
.then() 串接。複習完「同步」、「非同步」之後,我們來認識 Angular 自己使用的非同步工具 RxJS Observable。
我們一個個透過名詞解釋來了解:
Subscribe 訂閱一個 Observable 時(可以說是「監視」Observable 時XD),會回傳三種狀態:
三種狀態可以想像成 try、catch、finally 唷!
我們拿封裝好的 ApiServer 來執行非同步:
import { inject, signal } from '@angular/core';
import { AlertService } from '@/app/core';
import { ApiService } from '@/app/api';
export class Product {
private readonly alertService = inject(AlertService);
private readonly apiService = inject(ApiService);
readonly productList = signal<ProductType[]>([]);
protected refreshCaptcha(): void {
this.apiService.getProduct().subscribe({
next: (data: ProductType[]) => {
this.productList.set(data);
},
error: (err) => {
this.alertService.toastError(`請求錯誤!`)
},
complete: () => {
console.log('整個請求流程完成!')
}
}
}
如果元件被銷毀(Destroy)時沒有取消訂閱,非同步任務可能會持續在背景執行,導致記憶體洩漏(Memory Leak)。
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { UserService } from './user.service';
@Component({ ... })
export class UserComponent implements OnInit, OnDestroy {
users: any[] = [];
private sub!: Subscription;
constructor(private userService: UserService) {}
ngOnInit() {
// 手動訂閱並將資料賦值給本地變數
this.sub = this.userService.getUsers().subscribe(data => {
this.users = data;
});
}
ngOnDestroy() {
// 必須手動取消訂閱,否則會記憶體洩漏
if (this.sub) this.sub.unsubscribe();
}
}
就是這樣啦,一點一滴地釐清概念後,對 Angular 開發方式會更清楚唷!
繼續努力!
參考資料: