部署后清除模板缓存

dnd*_*ndr 10 angularjs

我想确保我的用户在部署后看到我的Angular应用程序的最新版本.在这种情况下清除模板缓存的正确策略是什么?

我读的地方,你可以做$templateCache.removeAll()app.run,但是这将禁用缓存完全,我认为?

Dra*_*usu 10

您需要编写一个拦截器并"捕获"所有模板请求 - 您应该能够在此拦截器中添加一个URL参数,该参数将对您的模板资产进行版本控制.

例:

// 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;
  }
};
Run Code Online (Sandbox Code Playgroud)

您当然需要在每次部署新版本时更新此应用程序配置(通过构建任务,您可以自动更新此文件).您可能需要添加额外的检查(例如,比较URL路径是否以".html"结尾),这样您就可以确定自己不是高举实际的HTTP请求.

这种方法的缺点是,有时您可能有一个未更新的模板,并且您不希望浏览器缓存被删除.如果这是你的情况,那么你应该为每个添加某种md5(templateContent) - 这也可以在构建时通过Grunt/Gulp实现.