我试图在角5中使用CacheStorage的承诺,就像在docs中一样:
let test = caches.open('test');
test.then((result : Cache) => {
result.add('/test.png')
})但我得到了:
ERROR Error: Uncaught (in promise): TypeError: the given value is not a Promise我试着在ts文件中从es5切换到es6。但同样的问题
谢谢
发布于 2018-08-29 17:47:23
在我的一个项目中,我也遇到了同样的问题。我希望我的应用程序在CacheStorage中存储一些资产。
我的代码看起来是这样的:
window.caches.open(CACHE_NAME)
.then(cache => cache.addAll(resources))
.catch(err => console.log('error while caching', err));我也犯了同样的错误:
ERROR Error: Uncaught (in promise): TypeError: the given value is not a Promise在搜索问题时,我发现Angular正在用自己的ZoneAwarePromise替换浏览器的全局ZoneAwarePromise实现,以跟踪承诺。不幸的是,CacheStorage以某种方式期望一个本地Promise而不是角的ZoneAwarePromise,并抛出一个错误。
我试图通过临时存储ZoneAwarePromise并用原始的Promise重新设置它来解决这个问题。事实证明,这是一个棘手的问题,结果导致我放弃了对实现的交换。
我找到了两个合适的解决方案--。
服务工作者<=>客户端通信
对于我的第二个(我认为是更好的)解决方案,我打开了一个用于客户端<=>服务工作人员通信的通道,并让服务工作人员执行动态缓存。
message事件侦听器。
服务工作者将侦听message事件,以接收和缓存来自客户端的urls列表。
self.addEventListener('message',event => { const = event.data;if (! urls ) { event.waitUntil(Promise.reject('nothing to cache'));event.ports.postMessage(false);}{ event.waitUntil( caches.open(version) .then(cache => cache.addAll( urls )) .then(self.skipWaiting()) .then(() => console.log('dynamic“) );event.ports.postMessage(true);}};controllerchange事件来触发重新缓存,如果新的服务工作人员正在控制。(见:服务工作者生命周期文档)。
const resources = 'some/url/to/cache.png‘、另一个/url/to/cache.css’navigator.serviceWorker.addEventListener('controllerchange',() => addToCache(resources) .then(data => console.log(‘url缓存“,data)) .catch(err => console.log('error .then,err) );不可见iframe
我针对这个问题的第一个解决方案实际上只是一次黑客攻击,但它目前还能工作。
const hiddenFrame = document.createElement('iframe');
hiddenFrame.style.display = 'none';
document.documentElement.appendChild(hiddenFrame);
hiddenFrame.contentWindow.caches.open(CACHE_NAME)
.then(cache => cache.addAll(resources))
.then(() => document.documentElement.removeChild(hiddenFrame))
.catch(err => console.log('error while caching', err));我在这里做的是:
我创建一个隐藏的iframe并将其附加到我的文档中。在iframe角内没有运行,因此存在本机Promise实现。然后从iframe的contentWindow对象访问缓存。成功缓存之后,我将删除iframe。
我还在找更好的解决办法。
我的下一个尝试是向服务工作者发送一条消息,并让它触发资源的缓存。服务人员也没有角度运行。
发布于 2018-09-10 05:41:04
这很容易被忽略-
1) CacheStorage API (或缓存API)仅在本地主机和HTTP/2上可用。
2)出于纯粹主义者的原因,倾向于使用window.caches.open(CACHE_NAME),因为caches是window对象中的一个单例实例。
https://stackoverflow.com/questions/49014332
复制相似问题