查過滿多資料的,Angular 不像 Vue、React 那樣會使用 Axios (少數,但還是有)。
大多數 Angular 的開發者會使用官方提供的 HTTP API HttpClient 來做 HTTP 請求。
HttpClient?HttpClient 是 Angular 封裝好的一個 HTTP API,基於瀏覽器原生的 XMLHttpRequest(XHR)介面 + RxJS 的結合,提供開發者更便利的網路請求解決方案。
Observable(可觀察對象),而非 Promise**。app.config.ts 設定,請求送出前或回應返回前進行統一處理,例如:Loading、錯誤訊息、自動附加 JWT Token......等。XMLHttpRequest,而非 Fetch API。HttpClient 提供 9 種請求方法:request | delete | get | head | jsonp | options | patch | post | put
用途為:
request<T>(method, url, options):萬用請求方法,可自由指定 HTTP 方法並能精細控制上傳或下載進度。delete<T>(url, options):刪除伺服器上的指定資源。get<T>(url, options):從伺服器取得資料。head<T>(url, options):向伺服器請求指定資源的 HTTP 回應標頭(Headers),而不下載實際內容。jsonp<T>(url, callbackParam):透過 JSONP 技術繞過瀏覽器同源政策限制,向不支援 CORS 的舊版第三方伺服器請求資料。options<T>(url, options):詢問伺服器該 URL 支援哪些 HTTP 方法、標頭或安全設定。patch<T>(url, body, options):更新伺服器上的現有資源(只修改部分欄位)。post<T>(url, body, options):向伺服器提交新資料並建立資源。put<T>(url, body, options):更新伺服器上的現有資源(完整覆蓋原本的資料)。HttpClient?app.config.ts 新增輔助函式 provideHttpClientimport { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
]
};
以下起手式記起來,每次無腦寫入就行了:
HttpClient、環境變數。http 的 HttpClient。this.http.HTTP方法(apiUrl, { params }) 呼叫後端。import { HttpClient } from '@angular/common/http';
import { ProductType } from '@/app/type';
import { environment } from '@/environments';
@Injectable({ providedIn: 'root' })
export class ApiService {
private readonly http = inject(HttpClient);
getProduct(): Observable<ProductType> {
return this.http.get<ProductType>(`${environment.apiUrl}/api/products`);
}
}
這樣拆解下來便不會那麼難懂了,大家也來試試看吧!
參考資料: