问题描述
我想在angularJS中缓存来自“ POST”请求的响应。
在Ajax中,“缓存= 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};