我想在 angularJS 中缓存来自“POST”请求的响应。
在 Ajax 中,“cache = true”仅适用于 GET 请求。我们如何使用 cacheFactory 或任何其他方法来实现它。
在下面,我想缓存特定 id 的“viewDetails”数据,而不是在点击时一次又一次地调用 ajax(反过来又是后端)。
此外,我如何每次都破坏缓存(cachefactory),它是否仅适用于特定会话并在会话关闭或需要明确破坏它时自行释放缓存。
任何帮助表示赞赏。
服务.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};
控制器.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};