我希望在部署Angular应用程序之后确保我的用户可以看到最新版本。在这种情况下清除模板缓存的正确策略是什么?
我在某个地方读到可以在 app.run
中执行 $templateCache.removeAll()
,但我想这将完全禁用缓存?
我希望在部署Angular应用程序之后确保我的用户可以看到最新版本。在这种情况下清除模板缓存的正确策略是什么?
我在某个地方读到可以在 app.run
中执行 $templateCache.removeAll()
,但我想这将完全禁用缓存?
// App .config()
$httpProvider.interceptors.push(function($templateCache) {
return {
'request' : function(request) {
if($templateCache.get(request.url) === undefined) { // cache miss
// Item is not in $templateCache so add our query string
request.url = request.url + '?appVersion=' + appService.getConfig().version;
}
return request;
}
};
当您部署新版本时,您当然需要更新此应用程序配置(通过构建任务,您可以自动更新此文件)。您可能需要添加额外的检查(例如,比较URL路径是否以“.html”结尾),以确保您没有劫持实际的HTTP请求。
这种方法的缺点是,有时您可能会使用未更新的模板,而您不希望浏览器缓存被破坏。如果是这种情况,请为每个模板内容添加某种md5值,这也可以通过Grunt/Gulp在构建时实现。
if(request.url.endsWith(".html")) {...}
就可以完美解决问题!我尝试了很多解决方案,但这个对我的用例来说是最好的。 - hmartos