fromFetch

2020-10-13 10:16 更新

使用 Fetch API 來 發(fā)出 HTTP 請求。

fromFetch<T>(input: string | Request, initWithSelector: RequestInit & { selector?: (response: Response) => any; } = {}): Observable<Response | T>

參量

輸入 您想獲取的資源。 可以是網(wǎng)址或請求對象。
initWithSelector 可選的。 默認值為 {}。         類型: RequestInit & { selector?: (response: Response) => any; }。

returns

Observable<Response | T>:一個 Observable,在訂閱時使用本機執(zhí)行 HTTP 請求 fetch 功能。 將 Subscription與綁定在一起以 AbortController進行抓取。

描述

警告 部分提取API仍處于試驗階段。 AbortController是 才能正常運行并適當使用取消功能。

會自動設置一個內部 AbortController 以便 拆除內部 fetch在訂閱取消時 。

如果 a signal通過 提供 init參數(shù) ,則其行為將與通常 fetch。 如果提供的內容 signal中止, 的錯誤 fetch通常會拒絕 在那種情況下,將被視為可觀察到的錯誤。

基本用途

  1. import { of } from 'rxjs';
  2. import { fromFetch } from 'rxjs/fetch';
  3. import { switchMap, catchError } from 'rxjs/operators';
  4. const data$ = fromFetch('https://api.github.com/users?per_page=5').pipe(
  5. switchMap(response => {
  6. if (response.ok) {
  7. // OK return data
  8. return response.json();
  9. } else {
  10. // Server is returning a status requiring the client to try something else.
  11. return of({ error: true, message: `Error ${response.status}` });
  12. }
  13. }),
  14. catchError(err => {
  15. // Network or other error, handle appropriately
  16. console.error(err);
  17. return of({ error: true, message: err.message })
  18. })
  19. );
  20. data$.subscribe({
  21. next: result => console.log(result),
  22. complete: () => console.log('done')
  23. });

與分塊傳輸編碼一起使用

對于使用 HTTP 響應 分塊傳輸編碼的 , 返回的諾言 fetch將在響應的標頭被解析后立即解析 收到。

這意味著 fromFetch可觀察者將發(fā)出 Response-并將 然后完成-在收到尸體之前。 當其中一種方法 Response-如 text()json()-被調用,返回的諾言將不會 解決,直到收到全身。 取消訂閱任何可觀察到的 使用 promise 作為可觀察輸入的操作不會中止請求。

為了便于中止使用分塊傳輸編碼的響應的檢索, 一個 selector可以通過指定 init參數(shù):

  1. import { of } from 'rxjs';
  2. import { fromFetch } from 'rxjs/fetch';
  3. const data$ = fromFetch('https://api.github.com/users?per_page=5', {
  4. selector: response => response.json()
  5. });
  6. data$.subscribe({
  7. next: result => console.log(result),
  8. complete: () => console.log('done')
  9. });
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號