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};
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};
Related
Upgrade to angularjs version 1.7 and this code does not compile
app.factory('LoginService', function ($http) {
return {
login: function (param, callback) {
$http.post(url, param)
.success(callback)
.error(function (data, status, headers, config) {
});
}
};
});
On the controller I make the call to the service LoginService
function LoginController($http, $location, LoginService, blockUI) {
var vm = this;
LoginService.usuario(
{login: vm.username, clave: vm.password},
function (data, status, headers, config) {
vm.resultado = data;
if (vm.resultado == "True") {
window.location = "/Home/Index";
} else {
vm.error = 'Usuario o password incorrecto';
}
});
};
I want to know how the function is called from the controller because it implemented the http.post service using .then
app.factory('LoginService', function ($http) {
return {
login: function (data) {
$http.post(url, data)
.then(function (resultado) {
debugger;
if (resultado.data === "True") {
return resultado.data;}
else {
console.log("NO");}
});
}};
});
I suggest you get familiar with a AngularJS $q service and its Promise API.
You LoginService.login(...) method should return the Promise from $http.post(...):
app.factory('LoginService', function ($http) {
return {
login: function (data) {
return $http.post(url, data)
.then(function(response) {
return response.data;
});
});
Then, your Controller can access the returned data via the resolved Promise:
function LoginController(LoginService) {
var vm = this;
LoginService.login({login: vm.username, clave: vm.password})
.then(function (result) {
// handle result here...
});
the solution would be this:
function LoginController($scope,$window,$q,LoginService) {
$scope.fnBusqueda = function () {
var promesas = [
obtenerLogin()
];
$q.all(promesas).then(function (promesasRes) {
var oArrayResponse = promesasRes;
if ((oArrayResponse.length > 0)) {
$scope.respuesta = oArrayResponse[0];
if ($scope.respuesta == "True") {
window.location = "/Home/Index";
} else {
$cope.error = 'Usuario o password incorrecto';
}
}
});
};
function obtenerLogin() {
var defered = $q.defer();
var promise = defered.promise;
LoginService.login(url_valida_login, '{login:X,clave:X}').then(function (response) {
defered.resolve(response);
}).catch(function (data) {
defered.resolve([]);
})
return promise;
}
}
I have a controller that passes execution to a factory -- controller.getCustomerById -> factory.getCustomerByID. In this case, the factory function is posting and retrieving data via MVC/angular.$http.post. That all works fine but the subsequent actions in my controller function are executing before the .post is finished.
I've tried making either or both async/await but I think I'm not understanding how to do that. I've tried quite a few of the examples here and elsewhere with no luck.
I have a button that calls setOrderFromGrid which calls getCustomerById. I would assume that making controller.getCustomerById an async function would be the best way but I can't get it to work.
angular.module('aps').factory('TechSheetFactory',
function($http) {
return {
//The ajax that is called by our controller
ITS: function(onSuccess, onFailure) {
const rvtoken = $("input[name='__RequestVerificationToken']").val();
$http({
method: "post",
url: "/DesktopModules/MVC/TechSheetMaint/TechSheet/InitializeNew",
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken
}
}).then(onSuccess).catch(onFailure);
},
saveTechSheetAng: function(onSuccess, onFailure, techSheetInfo) {
alert(JSON.stringify(techSheetInfo));
const rvtoken = $("input[name='__RequestVerificationToken']").val();
$http.post("/DesktopModules/MVC/TechSheetMaint/TechSheet/SaveTechSheetAng",
JSON.stringify(techSheetInfo),
{
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken,
'Content-Type': 'application/json'
}
}).then(onSuccess).catch(onFailure);
} ,
getCustomerById: function(onSuccess, onFailure, customerSearchString) {
alert('factory getcustomerbyid: ' + customerSearchString);
const rvtoken = $("input[name='__RequestVerificationToken']").val();
$http.post("/DesktopModules/MVC/TechSheetMaint/TechSheet/GetCustomerById",
{custId:customerSearchString},
{
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken,
'Content-Type': 'application/json'
}
}).then(onSuccess).catch(onFailure);
}
};
});
angular.module('aps').controller('TechSheetCtl', ['TechSheetFactory','$scope', '$rootScope', '$http', '$interval', '$modal', '$log','uiGridConstants',
function (TechSheetFactory,$scope, $rootScope, $http, $interval, $modal, $log) {
/* -----------------SaveTechSheet ------------*/
$scope.saveTechSheet = function() {
if (!$scope.dvTechSheet.$valid) {
$scope.Message = "Form not complete.";
$scope.Status = false;
$scope.showErrors=true;
return;
}
alert($scope.TechSheetInfo.Customer.CustomerID);
if (JSON.stringify($scope.TechSheetInfo.Customer) !== JSON.stringify($scope.TechSheetInfoStatic.Customer) &&
$scope.TechSheetInfo.Customer.CustomerID !== 0) {
if (confirm("You've made changes to this Customer. Save them?") !== true) {
return;
}
}
if (JSON.stringify($scope.TechSheetInfo.WorkOrder) !== JSON.stringify($scope.TechSheetInfoStatic.WorkOrder) &&
$scope.TechSheetInfo.WorkOrder.WorkOrderID !== 0) {
if (confirm("You've made changes to this Work Order. Save them?") !== true) {
return;
}
}
successFunction = function(response) {
var data = response.data.Data;
alert(data);
var techSheet = data.techSheet;
alert(data.status);
if (data.status) {
alert("looks good");
$scope.Message = "";
$scope.showErrors = false;
$scope.TechSheetInfo = techSheet;
alert($scope.TechSheetInfo);
$scope.TechSheetInfoStatic = angular.copy(techSheet);
$rootScope.customerInfo = techSheet.Customer;
createpdf($scope);
} else {
if (response.message !== null) {
$scope.Status = datae.status;
$scope.showErrors = true;
$scope.Message = data.message;
}
}
};
failureFunction = function(data) {
console.log('Error' + data);
};
TechSheetFactory.saveTechSheetAng(successFunction, failureFunction,$scope.TechSheetInfo);
};
/* ----------End SaveTechSheet ---------*/
//------------Initialize a new tech sheet. This is the default action for the page load/refresh/discard changes/clear form
$scope.initializeTechSheet = function() {
$scope.TechSheetInfo = [];
$scope.TechSheetInfoStatic = [];
$scope.customerIDDisabled = false;
$scope.orderIDDisabled = false;
$rootScope.customerInfo = [];
$scope.WindowsPassword = "";
$scope.EmailPassword = "";
const successFunction = function(response) {
$scope.TechSheetInfo = response.data;
$rootScope.customerInfo = response.data.Customer;
$scope.TechSheetInfoStatic = angular.copy(response.data);
};
const failureFunction = function(response) {
//console.log('Error' + response.status);
};
TechSheetFactory.ITS(successFunction, failureFunction);
};
//end initializeTechSheet
$scope.getCustomerById = function(custId) {
const successFunction = function(response) {
alert("success");
$scope.TechSheetInfo.Customer = response.data;
$scope.TechSheetInfoStatic.Customer = angular.copy(response.data);
$rootScope.customerInfo = response.data;
$scope.customerIDDisabled = true;
};
const failureFunction = function(data) {
alert('getcustomer fail');
console.log('Error' + JSON.stringify(data));
};
TechSheetFactory.getCustomerById(successFunction, failureFunction, custId);
};
$scope.setOrderFromGrid = function(woInfo) {
$scope.getCustomerById(woInfo.CustomerID);
$scope.TechSheetInfo.WorkOrder = woInfo; //this line and the next are occurring before getCustomerById has completed
$scope.TechSheetInfoStatic.Customer = angular.copy($scope.TechSheetInfo.Customer);
$scope.orderIDDisabled=true;
$scope.dvTechSheet.$setPristine();
};
$scope.resetForm = function() {
if (!$scope.dvTechSheet.$pristine) {
if (!confirm("Discard Changes?")) {
return;
}
}
$scope.initializeTechSheet();
$scope.dvTechSheet.$setPristine();
};
}]);
You lose the advantage of the Promises so you can opt-in a Promise this way. (I do not recommend it)
From the top of head something like this:
// inject $q
$scope.getCustomerById = function(custId) {
const deferred = $q.defer()
const successFunction = function(response) {
$scope.TechSheetInfo.Customer = response.data;
$scope.TechSheetInfoStatic.Customer = angular.copy(response.data);
$rootScope.customerInfo = response.data;
$scope.customerIDDisabled = true;
deferred.resolve(); // can pass value if you like
};
const failureFunction = function(data) {
alert('getcustomer fail');
console.log('Error' + JSON.stringify(data));
deferred.reject();
};
TechSheetFactory.getCustomerById(successFunction, failureFunction, custId);
return deferred.promise;
};
/////////////
$scope.setOrderFromGrid = function(woInfo) {
const prom = $scope.getCustomerById(woInfo.CustomerID);
prom.then(()=>{
$scope.TechSheetInfo.WorkOrder = woInfo;
$scope.TechSheetInfoStatic.Customer =
angular.copy($scope.TechSheetInfo.Customer);
$scope.orderIDDisabled=true;
$scope.dvTechSheet.$setPristine();
})
};
I am trying to make a GET call to test a REST API but it keeps returning null, is there anything I am doing wrong:
Making the call in controller.js
function ConsumerSearchCtrl($scope, BusinessCategoryService) {
console.log(BusinessCategoryService);
}
127.0.0.1:8000/api/category/ works perfectly fine
Code in services.js for API
/**
*
*/
function BusinessCategoryService(WenzeyAPI, $q) {
var scope = this;
scope.categories = categories;
function categories() {
var q = $q.defer();
WenzeyAPI.get('http://127.0.0.1:8000/api/category/').then(function success (res) {
q.resolve(res.data);
}, function failure (err) {
q.reject(err);
})
return q.promise;
}
}
/**
*
*/
function WenzeyAPI() {
var scope = this,
ip = "http://127.0.0.1:8000";
scope.get = get;
scope.post = post;
function get(url, data) {
data = data || {};
var req = {
method: 'GET',
url: url,
data: data
}
var q = $q.defer();
$http(req).then(function success(response) {
q.resolve(response);
}, function failure(err) {
q.reject(err);
});
return q.promise;
}
function post(url, data) {
data = data || {};
var req = {
method: 'POST',
url: url,
data: data
}
var q = $q.defer();
$http(req).then(function success(response) {
q.resolve(response);
}, function failure(err) {
q.reject(err);
});
return q.promise;
}
}
Removing WenzeyAPI and using $http resolved it.
function BusinessCategoryService($http) {
this.getAllData = function () {
return $http({
method: 'GET',
url: 'http://127.0.0.1:8000/api/category/',
});
}
}
I've ProductService and ProductsController. ProductService have ProductService.Products = []; variable which contains all the Products information.
I access this Products-information in ProductsController and stores in variable named $scope.Products = [];.
Problem is some other service also using "ProductService", and updating "Products Info", using "UpdateInfo" function exposed in ProductService. Now these changes are not getting reflected in ProductsController variable $scope.Products = [];.
This is my code.
sampleApp.factory('ProductService', ['$http', '$q', function ($http, $q){
var req = {
method: 'POST',
url: 'ProductData.txt',
//url: 'http://localhost/cgi-bin/superCategory.pl',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }//,
//data: { action: 'GET' }
};
var ProductService = {};
ProductService.Products = [];
return {
GetProducts: function () {
var defer = $q.defer();
$http(req).then(function(response) {
ProductService.Products = response.data;
defer.resolve(ProductService.Products);
}, function(error) {
defer.reject("Some error");
});
return defer.promise;
},
UpdateInfo: function (ProductID, VariantID) {
for (i in ProductService.Products) {
if (ProductService.Products[i].ProductID == ProductID) {
for (j in ProductService.Products[i].Variants) {
if (ProductService.Products[i].Variants[j].VariantID == VariantID) {
ProductService.Products[i].Variants[j].InCart = 1; /* Updating Info Here, But its not reflecting */
break;
}
}
break;
}
}
}
};
}]);
sampleApp.controller('ProductsController', function ($scope, $routeParams, ProductService, ShoppingCartService) {
$scope.Products = [];
$scope.GetProducts = function() {
ProductService.GetProducts().then
(
function(response) {
$scope.Products = response;
},
function(error) {
alert ('error worng');
}
);
};
$scope.GetProducts();
});
Can some one help me how to solve this issue?
You can create a $watch on ProductService.Products in your controller. When the value changes, you can update $scope.Products with the new value.
$scope.$watch('ProductService.Products', function() {
$scope.Products = ProductService.Products;
});
Try assigning ProductsService.Products to $scope.products.
$scope.GetProducts = function() {
ProductService.GetProducts().then
(
function(response) {
$scope.Products = ProductService.Products;
},
function(error) {
alert ('error worng');
}
);
};
I have following controller which is posting a new user and also getting new users.
The problem here is after adding a new user, the scope is not updated so view is not affected. I have also tired returning the function so it expects a promise but didnt update the scope.
myapp.controllers('users', ['usersService', ''$scope',', function(usersService, $scope){
getUsers();
function getUsers(params) {
if (typeof(params) === "undefined") {
params = {page: 1};
}
usersService.getUsers(params).then(function (res) {
$scope.users = res.items;
$scope.usersListTotalItems = res._meta.totalCount;
$scope.usersListCurrentPage = res._meta.currentPage + 1;
});
}
}
$scope.addUser = function (user) {
usersService.adddNewUser(user).then(function (response) {
getUsers();
});
}
}]);
myApp.factory('userService', ['Restangular', '$http', function (Restangular, $http) {
return {
getUsers: function (params) {
var resource = 'users/';
var users = Restangular.all(resource);
return users.getList(params)
.then(function (response) {
return {
items : response.data[0].items,
_meta : response.data[0]._meta
}
});
},
adddNewUser: function (items) {
var resource = Restangular.all('users');
var data_encoded = $.param(items);
return resource.post(data_encoded, {}, {'Content-Type': 'application/x-www-form-urlencoded'}).
then(function (response) {
return response;
},
function (response) {
response.err = true;
return response;
});
}
};
}]);
I think it is a small error however you did not include $scope in the argument for the controller function.
myapp.controllers('users', ['usersService','$scope', function(usersService $scope){
getUsers();
function getUsers(params) {
if (typeof(params) === "undefined") {
params = {page: 1};
}
usersService.getUsers(params).then(function (res) {
$scope.users = res.items;
$scope.usersListTotalItems = res._meta.totalCount;
$scope.usersListCurrentPage = res._meta.currentPage + 1;
});
}
}
$scope.addUser = function (user) {
usersService.adddNewUser(user).then(function (response) {
getUsers();
});
}
}]);