如何有效地缓存API,使用Angular CLI在Angular 5中使用Service worker [英] How API is getting cached effectively, Using Service worker in Angular 5 using Angular CLI

查看:93
本文介绍了如何有效地缓存API,使用Angular CLI在Angular 5中使用Service worker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是服务人员的新手。我只是想知道服务人员如何处理数据。



例如,我已经在其中配置了数据组并设置了策略性能 ,以便Service Worker始终在Cache中优先查看。这意味着在命中服务工作程序中注册的URL会在任何时候首先查找缓存。假设响应有一些变化(数据库中的数据已更改),响应将更新还是静止,它将从缓存中获取。



我在网上搜索了很多内容,但没有得到满意的答案。



配置

  dataGroups: [
{
name: task-user-api,
urls:[ / tasks, / users],
cacheConfig:
{
strategy: performance,
maxSize:20,
maxAge: 1h,
timeout: 5s
}
}
]


解决方案

经过几个小时的搜索,我找到了答案,有不同类型的缓存可用



a。 网络或缓存-服务于网络中的内容,但包括超时,如果来自网络的答案未按时到达缓存数据,则可以回退。



b。 仅缓存 –在安装Service Worker期间添加静态内容,并使用缓存来检索静态内容,无论网络是否可用。



c。 缓存和更新-缓存中的内容,并执行网络请求以获取新数据以更新缓存项,从而确保用户下次访问该页面时,他们将看到最新的内容。



d。 缓存更新和刷新 -为缓存中的内容提供服务,但同时执行网络请求以更新缓存条目,并通知UI有关新的最新消息



e。 嵌入式回退-嵌入回退内容,并在请求资源时发生故障时提供服务。



您可以阅读更多内容并获取每个代码来自


Am new to service worker. I just want to know how the service worker handling the Data changes.

For example, I have configured my data group in and set strategy to "performance" so that Service worker will always look first in Cache. That means any time the Registered URL in hit service worker will look in the cache first. Suppose the response has some changes ( data in database got changed ) will the response will update or still, it will take from the cache.

I searched quite a bit in net I didn't get a satisfying answer. if anybody can please help me

Cofiguration

"dataGroups":[
 {
   "name":"task-user-api",
   "urls":["/tasks","/users"],
   "cacheConfig":
    {
      "strategy" : "performance",
      "maxSize":20,
      "maxAge":"1h",
      "timeout":"5s"
    }
  }
]

解决方案

After few more hours of search, I found the answer to it, There are different type of caching available

a. Network or cache - Serve content from the network but include a timeout to fall back to cached data if the answer from the network doesn’t arrive on time.

b. Cache only -- Add static content during the installation of the service worker and use the cache to retrieve it whether the network is available or not.

c. Cache and Update -- Serve the content from the cache and also perform a network request to get fresh data to update the cache entry ensuring next time the user visits the page they will see up to date content.

d. Cache update and refresh -- Serve the content from the cache but at the same time, perform a network request to update the cache entry and inform the UI about new up to date content.

e. Embedded fallback -- Embed fallback content and serve it in case of a failure while requesting resources.

You can read more and get code for each implimentation from here

Complete code to get the Caching and alert on UI if anything changed on server

Service-worker.js

var cacheName = 'cache-update-and-refresh';;
var cacheFiles = [
    './',
    // list all the assests you want to list
]



self.addEventListener('install', function (e) {
    console.log("[serviceWorker] installed")

    e.waitUntil(
        caches.open('default-cache').then(function (cache) {
            return cache.addAll(cacheFiles)
        }).then(function () {
            return self.skipWaiting();
        }));
    console.log("[serviceWorker] Cached")
})

self.addEventListener('activate', (event) => {
    console.info('Event: Activate');
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames.map((cache) => {
                    if (cache !== cacheName) {     //cacheName = 'cache-v1'
                        return caches.delete(cache); //Deleting the cache
                    }
                })
            );
        })
    );
});

self.addEventListener('fetch', function (event) {
    event.respondWith(
        caches.match(event.request).then(function (response) {
            return response || fetch(event.request);
        })
    );
    event.waitUntil(
        update(event.request)
            .then(function (response) {
                caches.open(cacheName).then(function (cache) {
                    caches.match(event.request).then(function (cacheresponse) {
                            if (cacheresponse.headers.get("ETag") !== response.headers.get("ETag")) {
                                console.log('[ServiceWorker]' + response.url + ' - Cache' + cacheresponse.headers.get("ETag") + "- real" + response.headers.get("ETag"));
                                cache.put(event.request, response.clone()).then(function () {
                                    refresh(event.request, response);
                                });
                            }
                    });
                });
            })
    )
});

function fromCache(request) {
    return caches.open(cacheName).then(function (cache) {
        return cache.match(request);
    });
}

function update(request) {
    return caches.open(cacheName).then(function (cache) {
        return fetch(request).then(function (response) {
            return response;
        });
    });
}


function refresh(req, response) {
    return self.clients.matchAll().then(function (clients) {
        clients.forEach(function (client) {
            var message = {
                type: 'refresh',
                url: response,
                eTag: response.headers.get('ETag')
            };
            client.postMessage(JSON.stringify(message));
        });
    });
}

in Index.html

if ('serviceWorker' in navigator) {
    navigator.serviceWorker
        .register('./service-worker.js', { scope: './' })
        .then(function (registration) {
            console.log("Service worker registered", registration)
        })
        .catch(function (err) {
            console.log("Service Worker Failes to Register", err)
        })

    navigator.serviceWorker.addEventListener('message', function (event) {
        document.getElementById("cache-generic-msg").style.display = "block";
        console.log("Got reply from service worker: " + event.data);
    });

} 

Sequence diagram

这篇关于如何有效地缓存API,使用Angular CLI在Angular 5中使用Service worker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆