Angular 个模板的缓存问题

Caching issue with Angular templates

我正在测试使用 ui.router 和身份验证令牌的 Angular 应用程序。有一个部分页面仅供授权用户使用。以下是重现步骤:

1) 登录

2) 导航到部分用户个人资料页面

3) 注销

删除 $http.defaults.headers.common['x-access-token'];

4) 在浏览器地址栏中手动导航回个人资料页面。

5) 对个人资料页面的后续请求在没有令牌的情况下发出并被拒绝

Safari 中不会出现此问题。

这实际上是 Angular JS 缓存模板的一个已知问题。可悲的是,似乎没有解决方案。 '$templateCache.removeAll()' 对我不起作用。关于它的帖子很多:

AngularJS disable partial caching on dev machine

Remove Template cache on logout Angular.js

How to refresh / invalidate $resource cache in AngularJS

P.S. 实际上,有一个有效的解决方案:

http://opensourcesoftwareandme.blogspot.com/2014/02/safely-prevent-template-caching-in-angularjs.html

稍微修改后的版本如下所示:

$rootScope.$on('$stateChangeStart',
  function(event, toState, toParams, fromState, fromParams) {
    if (typeof(fromState.templateUrl) !== 'undefined'){
      $templateCache.remove(fromState.templateUrl);
    }
  });

经过更多研究,我发现了更好的解决方案。 '$templateCache.removeAll()' 实际上确实有效,除了模板仍然保存在某个地方并确保它们已更新我需要重新加载当前状态:

  $templateCache.removeAll();
  $state.transitionTo($state.current, $stateParams, {
    reload: true,
    inherit: false,
    notify: true
  });

这样我就不需要完全关闭缓存,而是可以在用户登录或注销时将其清除。