W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
除了從服務器獲取數(shù)據(jù)外,HttpClient
還支持其它一些 HTTP 方法,比如 PUT
,POST
和 DELETE
,你可以用它們來修改遠程數(shù)據(jù)。
本指南中的這個范例應用包括一個簡化版本的《英雄指南》,它會獲取英雄數(shù)據(jù),并允許用戶添加、刪除和修改它們。 下面幾節(jié)在 HeroesService
范例中展示了數(shù)據(jù)更新方法的一些例子。
應用經(jīng)常在提交表單時通過 POST
請求向服務器發(fā)送數(shù)據(jù)。 下面這個例子中,HeroesService
在向數(shù)據(jù)庫添加英雄時發(fā)起了一個 HTTP POST
請求。
Path:"app/heroes/heroes.service.ts (addHero)" 。
/** POST: add a new hero to the database */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}
HttpClient.post()
方法像 get()
一樣也有類型參數(shù),可以用它來指出你期望服務器返回特定類型的數(shù)據(jù)。該方法需要一個資源 URL 和兩個額外的參數(shù):
body
- 要在請求體中 POST
過去的數(shù)據(jù)。options
- 一個包含方法選項的對象,在這里,它用來指定必要的請求頭。該例子捕獲了前面所指的錯誤。
HeroesComponent
通過訂閱該服務方法返回的 Observable
發(fā)起了一次實際的 POST
操作。
Path:"app/heroes/heroes.component.ts (addHero)" 。
this.heroesService
.addHero(newHero)
.subscribe(hero => this.heroes.push(hero));
當服務器成功做出響應時,會帶有這個新創(chuàng)建的英雄,然后該組件就會把這個英雄添加到正在顯示的 heroes
列表中。
該應用可以把英雄的 id
傳給 HttpClient.delete
方法的請求 URL
來刪除一個英雄。
Path:"app/heroes/heroes.service.ts (deleteHero)" 。
/** DELETE: delete the hero from the server */
deleteHero (id: number): Observable<{}> {
const url = `${this.heroesUrl}/${id}`; // DELETE api/heroes/42
return this.http.delete(url, httpOptions)
.pipe(
catchError(this.handleError('deleteHero'))
);
}
當 HeroesComponent
訂閱了該服務方法返回的 Observable
時,就會發(fā)起一次實際的 DELETE
操作。
Path:"app/heroes/heroes.component.ts (deleteHero)" 。
this.heroesService
.deleteHero(hero.id)
.subscribe();
該組件不會等待刪除操作的結果,所以它的 subscribe
(訂閱)中沒有回調函數(shù)。不過就算你不關心結果,也仍然要訂閱它。調用 subscribe()
方法會執(zhí)行這個可觀察對象,這時才會真的發(fā)起 DELETE
請求。
注:
- 你必須調用
subscribe()
,否則什么都不會發(fā)生。僅僅調用HeroesService.deleteHero()
是不會發(fā)起DELETE
請求的。
// oops ... subscribe() is missing so nothing happens
this.heroesService.deleteHero(hero.id);
在調用方法返回的可觀察對象的 subscribe()
方法之前,HttpClient
方法不會發(fā)起 HTTP 請求。這適用于 HttpClient
的所有方法。
AsyncPipe 會自動為你訂閱(以及取消訂閱)。
HttpClient
的所有方法返回的可觀察對象都設計為冷的。 HTTP 請求的執(zhí)行都是延期執(zhí)行的,讓你可以用 tap
和 catchError
這樣的操作符來在實際執(zhí)行 HTTP 請求之前,先對這個可觀察對象進行擴展。
調用 subscribe(...) 會觸發(fā)這個可觀察對象的執(zhí)行,并導致
HttpClient` 組合并把 HTTP 請求發(fā)給服務器。
你可以把這些可觀察對象看做實際 HTTP 請求的藍圖。
實際上,每個
subscribe()
都會初始化此可觀察對象的一次單獨的、獨立的執(zhí)行。 訂閱兩次就會導致發(fā)起兩個 HTTP 請求。
<br>const req = http.get<Heroes&('/api/heroes'); <br>// 0 requests made - .subscribe() not called. <br>req.subscribe(); <br>// 1 request made. <br>req.subscribe(); <br>// 2 requests made. <br>```
應用可以使用 HttpClient
服務發(fā)送 PUT
請求。下面的 HeroesService
示例(就像 POST
示例一樣)用一個修改過的數(shù)據(jù)替換了該資源。
Path:"app/heroes/heroes.service.ts (updateHero)" 。
/** PUT: update the hero on the server. Returns the updated hero upon success. */
updateHero (hero: Hero): Observable<Hero> {
return this.http.put<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('updateHero', hero))
);
}
對于所有返回可觀察對象的 HTTP 方法,調用者(HeroesComponent.update()
)必須 subscribe()
從 HttpClient.put()
返回的可觀察對象,才會真的發(fā)起請求。
很多服務器都需要額外的頭來執(zhí)行保存操作。 例如,服務器可能需要一個授權令牌,或者需要 Content-Type
頭來顯式聲明請求體的 MIME
類型。
HeroesService
在一個 httpOptions
對象中定義了這樣的頭,它們被傳遞給每個 HttpClient
的保存型方法。
Path:"app/heroes/heroes.service.ts (httpOptions)" 。
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
你不能直接修改前面的選項對象中的 HttpHeaders
請求頭,因為 HttpHeaders
類的實例是不可變對象。請改用 set()
方法,以返回當前實例應用了新更改之后的副本。
下面的例子演示了當舊令牌過期時,可以在發(fā)起下一個請求之前更新授權頭。
httpOptions.headers =
httpOptions.headers.set('Authorization', 'my-new-auth-token');
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: