【发布时间】:2017-11-10 10:13:08
【问题描述】:
我正在为我的应用程序使用 AngularJS 1.6 和 Typescript,我想知道是否有办法在 TypeScript 中编写 Service Worker?
当我用谷歌搜索时,我发现了很多用 Angular2 编写它的技巧,但我对 Angular2 没有任何经验。
我之前已经写过服务工作者,但它是用纯 js 编写的,考虑到我使用的是打字稿,我应该创建一个服务还是其他东西?我知道纯 java 脚本可以工作,但我认为这不是一个好方法,因为我主要在应用程序的其余部分使用 typescript。
我想在类等中重写这样的东西:
var cacheWhiteList = [];
cacheWhiteList.push(cacheName);
cacheWhiteList.push(dataCacheName);
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching app shell');
return cache.addAll(filesToCache.map(url => new Request(url, {
credentials: 'same-origin'
})));
})
);
});
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
console.log('[ServiceWorker] Removing old cache', key);
if (cacheWhiteList.indexOf(key) === -1) {
return caches.delete(key);
}
}));
})
);
});
self.addEventListener('push', function(event) {
console.log('Push message received', event);
var notificationBody = "";
event.waitUntil(
fetch('/api/Deploy/LastReleases', {
method: 'get',
credentials: 'same-origin'
}).then(function(response) {
return response.text();
}).then(function(text) {
notificationBody = text;
console.log("body1:" + notificationBody);
var title = 'UDD DELIVERY';
self.registration.showNotification(title, {
body: notificationBody,
icon: '/Content/images/icons/icon-120x120.png',
vibrate: [300, 100, 300],
tag: 'Release-tag',
requireInteraction: true
})
})
);
});
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(clients.matchAll({
includeUncontrolled: true,
type: 'window'
}).then(activeClients => {
if (activeClients.length > 0) {
activeClients[0].navigate('/');
activeClients[0].focus();
} else {
clients.openWindow('/');
}
}));
});
self.addEventListener('fetch', function(e) {
var dataUrl = '/api/';
var dataUrl2 = '/api/Deploy/LastReleases';
var dataUrl3 = '/api/deploy/Register';
if (e.request.url.indexOf(dataUrl) > 0) {
if (e.request.url.indexOf(dataUrl2) > 0 || e.request.url.indexOf(dataUrl3) > 0) {
e.respondWith(
fetch(e.request)
.then(function(response) {
return response;
})
);
} else {
e.respondWith(
fetch(e.request)
.then(function(response) {
return caches.open(dataCacheName).then(function(cache) {
cache.put(e.request.url, response.clone());
return response;
});
})
);
}
} else {
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request);
})
)
};
});
【问题讨论】:
标签: javascript angularjs typescript service-worker progressive-web-apps