如何缓存AngularJS部分



gangularjs生产中最简单/现代的方法是什么?

当前代码看起来像:

$routeProvider.when('/error', {templateUrl: 'partials/error.html', controller: 'ErrorCtrl'});

templateUrl显然是单独文件的HTTP路径。在移动设备上,该文件的加载时间很明显,我很想只缓存所有内容。

答案的主要部分是$ templatecache。提取物:

var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
    $templateCache.put('templateId.html', 'This is the content of the template');
});

任何HTML模板都可以移动到$templateCache,我们的其余应用程序将按照预期(无需其他更改)的作用)

局部存储作为缓存

,如果我们想将模板保留在客户端上,我们也可以使用本地存储。这个角度 - 本地存储扩展可以简化很多东西。

所以,让我们将run()调整为

  1. 观察local-storage,如果我们在客户端上还没有模板
  2. 发出加载最新的请求...
  3. 将其放入缓存(local-storage$templateCache

调整后的代码

.run([                  'localStorageService','$templateCache','$http',
    function myAppConfig(localStorageService , $templateCache , $http) {
    // The clearAll() should be called if we need clear the local storage
    // the best is by checking the previously stored value, e.g. version constant 
    // localStorageService.clearAll();
    var templateKey = "TheRealPathToTheTemplate.tpl.html";
    // is it already loaded?
    var template = localStorageService.get(templateKey);
    // load the template and cache it 
    if (!template) {
        $http.get(templateKey)
            .then(function(response) {
                // template loaded from the server
                template = response.data;
                localStorageService.add(templateKey, template);
                $templateCache.put(templateKey, template);
            });
    } else {
        // inject the template
        $templateCache.put(templateKey, template);
    }
    }])

所以,这样,我们从local-storage中获利。它充满了服务器中的"模板",保留在那里...因此下次未加载。

注意:非常重要的是,还要注入一些version键/值并进行检查。如果本地存储过时...所有模板都必须重新加载。

最新更新