大多數前端應用都需要通過 HTTP 協議與后端服務器通訊。現代瀏覽器支持使用兩種不同的 API 發起 HTTP 請求:XMLHttpRequest 接口和 fetch() API。
@angular/common/http中的HttpClient類為 Angular 應用程序提供了一個簡化的 API 來實現 HTTP 客戶端功能。它基於瀏覽器提供的 XMLHttpRequest 接口。
HttpClient帶來的其它優點包括:可測試性、強類型的請求和響應對象、發起請求與接收響應時的攔截器支持,以及更好的、基於可觀察(Observable)對象的 API 以及流式錯誤處理機制。
添加服務
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
//帶類型檢查的響應
export class HttpResult<T> {
Data: T;
Status: number;
}
@Injectable()
export class ChannelService {
constructor(private http: HttpClient) { }
getChannel(id: string) {
return this.http.post<HttpResult<any>>('api/Portal/Channel/Get', {id:id}).pipe(
retry(3), // 對失敗的 Observable 自動重新訂閱幾次
catchError(this.handleError) // then handle the error
);
}
}
添加請求頭
很多服務器在進行保存型操作時需要額外的請求頭。 比如,它們可能需要一個 Content-Type 頭來顯式定義請求體的 MIME 類型。 也可能服務器會需要一個認證用的令牌(token)。
@angular/common/http中的HttpHeaders類對象中就定義了一些這樣的請求頭
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
發起一個 POST 請求
HttpClient.post()方法它包含一個資源 URL,還接受另外兩個參數:
-
data- 要
POST的請求體數據。 -
HTTPOtions - 這個例子中,該方法的選項指定了所需的請求頭。
//保存表單數據 saveChannel(data) { return this.http.post<HttpResult<any>>('api/Portal/Channel/Save', data, httpOptions).pipe( catchError(this.handleError) // then handle the error ); }
