LoginSignup
32
32

More than 5 years have passed since last update.

AngularJSで外部APIコールをキャッシュする

Last updated at Posted at 2014-06-10
  • 一番簡単に実現するには、$http サービスで外部APIコール時に cache: ture オプションを渡します。
    • cacheFactory 内の $http という名称の領域にキャッシュされます。
'use strict';

angular.module('apiTestApp')
  .factory('JsonData', ['$http', function ($http) {

    return {

      getSampleData: function () {

        return $http.get('data/sample.json', {cache: true})
          .success(function(data, status, headers, config) {

            return data;

        });

      }

    }

  }])
;
  • きちんとキャッシュされているか否かは、Chrome の Developer Tools で確認できます。
    • 2回目以降はAPIコールがされなければOK(後述しますがキャッシュ先はヒープメモリなので、ブラウザをリロードするとキャッシュは消えてしまうので注意)。

スクリーンショット 2014-06-10 12.58.18.png

  • もしキャッシュの挙動を変えたい場合は、独自の Factory を作成します。
    • 下の例では、独自に apiCache という Factory を作成し、cacheFactory 内の api という名称の領域にキャッシュさせています。
    • この際、capacity オプションを指定し、最も利用されている10件のみキャッシュするようにしています。
'use strict';

angular.module('apiTestApp')
  .factory('apiCache', function($cacheFactory) {

    return $cacheFactory('api', {capacity: 10});

  })
  .factory('JsonData', ['$http', 'apiCache', function ($http, apiCache) {

    return {

      getSampleData: function () {

        return $http.get('data/sample.json', {cache: apiCache})
          .success(function(data, status, headers, config) {

            return data;

        });

      }

    }

  }])
;

補足

  • キャッシュ先およびアルゴリズムは $cacheFactory に準じます。
    • キャッシュ先はヒープメモリです。
      • ブラウザをリロードするとキャッシュは消えます。
    • capacity オプションを指定した際、LRUアルゴリズムが適用されます。

参考

ほか

32
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
32