Anand
Anand

Reputation: 1

How to cache response for Ajax 'POST' Request in AngularJS

I want to cache response from "POST" request in angularJS.
In Ajax, "cache = true" works only for GET request. How can we achieve it using cacheFactory or any other method.

Here below I want to cache 'viewDetails' data for particular id and not call ajax(in turn backend) again and again on click.

Also, How do I bust the cache everytime(cachefactory), is it only for particular session and release cache itself once session is closed or need to bust it explicitly.
Any help is appreciated.

service.js.

import {moduleName} from "../config/constants";

const serviceName = `${moduleName}_dataService`;

angular.module(moduleName).factory(serviceName, service);
service.$inject = ['$q', '$http'];

function service($q, $http) {

return {
    getDetailsData: getDetailsData
};

function getDetailsData(payload) {
    const def = $q.defer();
           
    const promise = $http({
        method: 'POST',
        url: '/order/gentrular-db/viewDetails',
        data: payload
    });
    
      promise.then(
        (response) => {
            if (typeof response.data === 'undefined' || response.data === null) {
                def.reject("Empty response body");
                return;
            }           
            def.resolve(response.data);
        },
        (error) => {
            def.reject(error.status);
        });
        
    return def.promise;
}

}

export {serviceName};  

controller.js:

import {serviceName as dataServiceName} from "../../services/detailsDataService";

controller.$inject = ['$scope', dataServiceName];

function controller($scope, dataService) {

    const $ctrl = this;

    // Input binding
    $ctrl.productId = null;
    $ctrl.onClickClose = null;

    // Local binding
    $ctrl.$onInit = onInit;
    $ctrl.ready = false;
    $ctrl.productDetailSection = null;
    $ctrl.clinicalSection = null;
    $ctrl.importantInformationSection = null;
    $ctrl.close = close;

    function onInit() {
        const promise = dataService.getDetailsData(buildPayload());
        promise.then((data) => {
            $ctrl.productDetailSection = data.productDetailSection;
            $ctrl.clinicalSection = data.clinicalSection;
            $ctrl.importantInformationSection = data.impInformationSec;
            $ctrl.ready = true;
        });
    }

    function buildPayload() {
        return {
            productType: "hortiz",
            productId: $ctrl.productId
        };
    }

    function close() {

        if (angular.isFunction($ctrl.onClickClose)) {
            $ctrl.onClickClose();
        }

    }

}

export {controller};

Upvotes: 0

Views: 98

Answers (1)

Anand
Anand

Reputation: 1

I was able to cache response using cacheFactory. Here is my working code.

import {moduleName} from "../config/constants";
const serviceName = `${moduleName}_dataService`;

angular.module(moduleName).factory(serviceName, service);

service.$inject = ['$q', '$http', '$cacheFactory'];

function service($q, $http, $cacheFactory) {

    return {
        getDetailsData: getDetailsData
    };

    function getDetailsData(payload,productId) {
        var cache = $cacheFactory.get('detailsDataCache') || $cacheFactory('detailsDataCache');
        var cacheId = productId;
        var cachedData = cache.get(cacheId);    
        
        const def = $q.defer();
        
        if (!cachedData) {

            const promise = $http({
                method: 'POST',
                url: '/order/gentrular-db/viewDetails',
                data: payload
            });

            promise.then(
                (response) => {
                    if (typeof response.data === 'undefined' || response.data === null) {
                        def.reject("Empty response body");
                        return;
                    }
                    cache.put(cacheId, response.data);
                    def.resolve(response.data);
                },
                (error) => {
                    def.reject(error.status);
                });
        }else {
            return $q.when(cachedData); 
        }
            return def.promise;
    }

}

export {serviceName};

Upvotes: 0

Related Questions