一般的 Web 應用程式,如果 Server 端連不上了,就會直接 GG (在 Chrome 上 恐龍就出現了)。是否有什麼方式在 Client 端程式與 Server 端之間有一個 Buffer 呢?
讓應用系統會整個 GG 呢? 答案就是 Service Worker 。
Service Worker 就像是一個 Middleware 一樣,在 Client 端程式與 Server 端之間,如下圖所示,

而各 Browser 的 Support 狀況可以參考 Service Worker - Platform status
那我們在 Angular (筆者使用的版本是 Angular CLI v 1.6.0) 中要如何使用 Service Worker 呢?
1.寫 Service Worker 的 js 檔(sw.js 放在 src 目錄下)。

2.在 .angular-cli.json 中 Apps -> assets 中加入 sw.js。

3.main.ts 註冊 service worker (sw.js)。
1 | platformBrowserDynamic() |
那 Service Worker 要寫些什麼呢?
它是 event base 的,而它的 event Life Cycle 可以參考以下的圖,

舉個簡單的例子,在 Angular 首頁中讀取 /api/lessons 的課程資料下來呈現,如下圖,

所以在 Service Worker (sw.js) 中就可以在 install event 中將這些 Resource 存到 Cache 之中。在 fetch event 中,就從 Cache 中取得這些 Resource,如下,
1 | const VERSION = 'v1'; |
所以從開發工具的 Application (左邊選 Service Workers)可以發現,sw.js 已經 activated 及 running ,在 Cache Storage 也儲存我們要 Cache 的資源 。如下圖,


然後我們在開發工具的 Application 中勾選 offline 後,再重新整理頁面,可以發現我們的頁面可以正常的顯示哦! 如下圖,
