[英]Angular PWA and NGRX.. fetch data if offline
我想問一下,即使 angular 應用程序由於網絡或沒有互聯網而關閉,我是否仍然可以使用 ngrx 檢索數據。 這個想法就像..如果沒有互聯網,則提取到目前為止已保存在商店中的默認數據。
對於簡約的 PWA,您需要執行以下操作:
首先,您將 service worker 注冊到:
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/serviceworker.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
首先,您檢查它是否在您的瀏覽器中可用。 如果是,那么您需要將路徑傳遞給您的服務人員。 在此示例中,它/serviceworker.js
。
請記住:如果您使用 HTTP 或文件系統C://
,則注冊將不起作用,您需要使用 HTTPS 或 localhost 它也應該可以工作。
現在是服務人員部分。 使用此示例,您將緩存您訪問的每個頁面,並且如果您關閉網絡,它仍然可以工作。
//serviceworker.js
var CACHE_NAME = "my_cache_v1";
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request).then(
function(response) {
// Check if we received a valid response
if(!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// IMPORTANT: Clone the response. A response is a stream
// and because we want the browser to consume the response
// as well as the cache consuming the response, we need
// to clone it so we have two streams.
var responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(event.request, responseToCache);
});
return response;
}
);
})
);
});
您可以使用 PWA 做更多事情。 您可以要求用戶安裝您的應用程序,也可以為用戶訂閱推送通知。 實際上,我在一個小型庫上工作,應該為您簡化它,您可以在這里查看:(仍在開發中)
https://github.com/ilijanovic/serviceHelper
https://www.npmjs.com/package/servicehelper
要使其可安裝,您需要在您的站點中包含一個具有基本屬性的清單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.