HttpClient 是 Angular 對 XMLHttpRequest 和 Fetch 的封裝
理解 HttpClient
provideHttpClient 源碼在 provider.ts
1 | export function provideHttpClient( |
- HttpClient 是最常用的Service Providers
- Angular 默認內部使用XMLHttpRequest發送請求
全局載入
- 添加 HttpClient 相關的 providers
app.config.ts1
2
3
4
5
6
7
8
9
10
11
12
13
14
15import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
+ import {provideHttpClient} from '@angular/common/http';
import { routes } from './app.routes';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
// 添加 HttpClient 相關的 providers
+ provideHttpClient(),
provideRouter(routes),
provideClientHydration(withEventReplay())
]
};Fetch 不支持上傳進度,這個是 Fetch 目前最大的缺陷,這也是為什么 Angular 任然以 XMLHttpRequest 作为默認。
src/app 新增 api 資料夾 => 新增 web-api.service.ts
1 | import { Injectable, inject } from '@angular/core'; |
src/app 新增 api 資料夾=> 新增http-provider.service.ts
1 | import { Injectable, inject } from '@angular/core'; |
參考資料
- XMLHttpRequest
- Fetch
- RxJS