angularjs: how to add caching to resource object?

后端 未结 8 682
栀梦
栀梦 2020-12-02 08:08

To add caching inside http is pretty straight forward. ( by passing cache=true )

http://docs.angularjs.org/api/ng.$http has Cache option.

How do I add simila

8条回答
  •  星月不相逢
    2020-12-02 08:53

    Looking at the angular-resource source indicates that triggering caching isn't possible with the way it is currently written.

    Here's the request object from the source:

    $http({
        method: action.method,
        url: route.url(extend({}, extractParams(data), action.params || {}, params)),
        data: data
     }).then(...)
    

    There are a few potential ways to deal with this.

    First, you could cache locally using client-side persistence. I use amplify.store with wrapper (b/c I don't really like the API syntax). There are a variety other storage solutions depending on what you're looking for and what browser's your targeting. Quite a few people use lawnchair as well.

    You can then stringify and store your models locally and update them based on whatever rules or time limits you desire.

    Another solution is to simply modify angular resource to accept the parameters you're looking for. This could be as simple (simply add an additional argument to $resource) or complex as you need it to be.

    e.g.

    function ResourceFactory(url, paramDefaults, actions, cache) {
       ...
       var cache = cache != null ? cache : false; // Set default to false
       $http({
            method: action.method,
            url: route.url(extend({}, extractParams(data), action.params || {}, params)),
            data: data,
            cache: cache
        }).then(...)       
    }
    

    Finally, depending on you requirements, it might be significantly easier to simply create your own resource, using angular.factory to create a service. One of the advantages of ngResource is that is does all of the string interpolation work for you when translating parameters. However, you can certainly barrow this logic for parsing if you need it, or write your own based on the models you're using.

提交回复
热议问题