如何在 AngularJS 中缓存 Ajax 'POST' 请求的响应



我想缓存来自"POST";angularJS中的请求
在Ajax中;cache=true";仅适用于GET请求。我们如何使用cacheFactory或任何其他方法来实现它。

在下面,我想缓存特定id的"viewDetails"数据,而不是在单击时一次又一次地调用ajax(反过来是后端(。

此外,我如何每次都破坏缓存(cachefactory(,它是否只针对特定会话,并在会话关闭或需要明确破坏时释放缓存本身
如有任何帮助,我们将不胜感激。

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};

我能够使用cacheFactory缓存响应。这是我的工作代码。

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};

最新更新