data from one angular call method to another method as parameter - angularjs

The following is the code structure, iam using hot towel template for mvc project.
The script:
(function () {
'use strict';
var controllerId = 'EditEmployeeController';
angular.module('app').controller(controllerId, ['common', 'EmployeeService', EmployeeData]);
function EmployeeData(common, EmployeeService) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var $filter = common.$filter;
var logError = common.logger.getLogFn('app', 'error');
var vm = this;
vm.CountryCode;
vm.Country = [];
vm.State = [];
vm.employeeInfo = {};
//calling the method to get the Employee info
activate();
//calling the methods to get the States
GetStates();
function activate() {
var promises = [GetEmployeeInfo(),GetStates()];
common.activateController(promises, controllerId)
.then(function () { });
}
}
function GetEmployeeInfo() {
return EmployeeService.getEmpInfoForEdit(personId).then(function (data) {
vm.CountryCode = data.Country;
return vm.employeeInfo = data;
}
function GetStates() {
return EmployeeService.getStates(vm.CountryCode).then(function (data) {
return vm.State = data;
}
}
})();
EmployeeService.js
code snippet from EmployeeService.js
function getEmpInfoForEdit(personId) {
var EmpInfoForEdit = $resource('Employee/GetEmployeeDetailsForEdit', angular.fromJson(personId), { 'query': { method: 'POST', isArray: false } });
var deferred = $q.defer();
EmpInfoForEdit.query({}, function (response) {
deferred.resolve(response);
}, function (error) {
deferred.reject(error);
})
return deferred.promise;
}
vm.CountryCode always shows null, though we are assigning a value to it in the GetEmployeeInfo method.Because unable to get the states.
please let me know can we get the data into vm.CountryCode ?

(function () {
'use strict';
var controllerId = 'EditEmployeeController';
angular.module('app').controller(controllerId, ['common', 'EmployeeService', EmployeeData]);
function EmployeeData(common, EmployeeService) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var $filter = common.$filter;
var logError = common.logger.getLogFn('app', 'error');
var vm = this;
vm.CountryCode=[];
vm.Country = [];
vm.State = [];
vm.employeeInfo = {};
//calling the method to get the Employee info
activate();
//calling the methods to get the States
GetStates();
function activate() {
var promises = [GetEmployeeInfo(),GetStates()];
common.activateController(promises, controllerId)
.then(function () { });
}
}
function GetEmployeeInfo() {
return EmployeeService.getEmpInfoForEdit(personId).then(function (data) {
vm.CountryCode = data.Country;
return vm.employeeInfo = data;
}
function GetStates() {
return EmployeeService.getStates(vm.CountryCode).then(function (data) {
return vm.State = data;
}
}
})();

If you want to work with the EmployeeService.getEmpInfoForEdit and EmployeeService.getStates returned data, you should inject $q in your controller and use the resolve data as the following example :
angular.module('app').controller(controllerId, ['$q', 'common', 'EmployeeService', EmployeeData]);
...
function GetEmployeeInfo() {
var deferred = $q.defer();
return EmployeeService.getEmpInfoForEdit(personId).then(function (data) {
deferred.resolve(data);
}
}
function GetStates() {
var deferred = $q.defer();
return EmployeeService.getStates(vm.CountryCode).then(function (data) {
deferred.resolve(data);
}
}

the issue is resolved by moving the GetStates method inside the then
var promises = [GetEmployeeInfo(),GetStates()];
common.activateController(promises, controllerId)
.then(function () { });
}
}
changed to
var promises = [GetEmployeeInfo()];
common.activateController(promises, controllerId)
.then(function () { GetStates() });
}
}

Related

how to get response of 2 api calls in angular js with $q.all and service

i want to call 2 api and want to store the response in the scope variable. but im not able to get the data in the scope variable. im using $q.all and service for calling the api
error
angular.js:88 Uncaught Error: [$injector:modulerr]
var app = angular.module('mymodule', []);
app.service('doorService', function ($http) {
this.get = function () {
var response = $http.get("url");
console.log(response);
alert("test");
return response;
};
});
app.service('waterService', function ($http) {
this.get = function () {
var response = $http.get("url");
return response;
};
});
app.controller('ctrl', function ($scope, $q, doorService, waterService) {
$scope.DoorData = [];
$scope.WatertankData = [];
loadData();
function loadData() {
var promiseDoor = doorService.get();
var promiseWater = waterService.get();
$scope.combineResult = $q.all([
promiseDoor,
promiseWater
]).then(function (resp) {
$scope.DoorData= resp[0].data;
$scope.WatertankData= resp[1].data;
});
}
});
function loadData() {
var promises = [
doorService.get(),
waterService.get()
];
$q.all(promises).then(function (resp) {
$scope.DoorData= resp[0].data;
$scope.WatertankData= resp[1].data;
$scope.combineResult = {
'DoorData': resp[0].data,
'WatertankData':resp[1].data
};
});
}

Calling only once or caching the data from a $http get in an AngularJS service

I have a simple app in DNN. Below is my code.
What am I trying to do is create a service which call the GET api once. So when the same data from input were called twice the service will call the same api. I'm using network in inspect element to find the calling functions.
<script type="text/javascript">
'use strict';
var myApp<%=ModuleId%> = {};
var isDlgOpen;
try {
myApp<%=ModuleId%> = angular.module('myApp<%=ModuleId%>', ['ngMaterial', 'ngMessages']);
}
catch (e) {
myApp<%=ModuleId%> = angular.module('myApp<%=ModuleId%>', ['ngMaterial', 'ngMessages']);
}
//Service
myApp<%=ModuleId%>.service('myService', ['$http', '$q', function ($q, $http) {
this.data;
var self = this;
this.submit = function () {
if (angular.isDefined(self.data)) {
return $q.when(self.data)
}
return $http.get($scope.apiGetUrl).then(function (response) {
self.data = response;
})
}
}]);
//Controller
myApp<%=ModuleId%>.controller('myCtrlr<%=ModuleId%>', function (myService, $scope, $http, $mdDialog) {
$scope.submit = function (ev) {
$scope.portalAlias = 'http://<%=PortalSettings.PortalAlias.HTTPAlias %>';
$scope.apiGetUrl = $scope.portalAlias + '/desktopmodules/ORSIModule/api/RepairStatus/getRepair?JobNo=' + $scope.jobNo + '&SerialNo=' + $scope.serialNo;
//form is valid
if ($scope.myForm.$valid) {
$scope.isLoading = true;
return $http.get($scope.apiGetUrl).then(
function (response) {
if (response.data) {
$scope.myForm.$setSubmitted();
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('dnnModule<%=ModuleId%>')))
.clickOutsideToClose(true)
.title('title: ' + response.data.status)
.textContent('Thank you.')
.ariaLabel('Status Alert Dialog')
.ok('Close')
.targetEvent(ev)
.hasBackdrop(false)
);
} else {
alert("Not found.");
}
});
}
};
});
// Bootstrap the module
var appDiv = document.getElementById("dnnModule<%=ModuleId%>");
angular.bootstrap(appDiv, ["myApp<%=ModuleId%>"]);
Please somebody help me thanks
You just need to set the cache property to true in the get request:
$http.get(url, { cache: true}).success(...);
Also you can use:
$http({ cache: true, url: url, method: 'GET'}).success(...);
Another approach is to use cachefactory service:
var cache = $cacheFactory('myCache');
var data = cache.get(someKey);
if (!data) {
$http.get(url).success(function(result) {
data = result;
cache.put(someKey, data);
});
}

Angular pass parameters and receive json

I am using this service to get json data. How can I pass two parameters as well. With the json I need to populate a drop down.
myApp.service('allCurrentSettingsService', ['$http', '$q', function ($http, $q) {
var allSettings = null;
this.getList = function () {
var def = $q.defer()
if (allSettings) {
def.resolve(allSettings);
} else {
$http.post('GetAllCurrentSettings', { companyName: compName, customerName: custName })
.then(function (response) {
var response = $.parseJSON(response.data)
allSettings = response;
def.resolve(allSettings);
});
}
return def.promise;
}
}]);
And here I am calling the service:
myApp.controller('myController', ['$scope', 'getDocTypesService',
function ($scope, getDocTypesService) {
$scope.getDocTypes = '';
getDocTypesService.getList(compName, custName).then(function (value ) {
$scope.getDocTypes = value
});
}
]);
You missed the function parameters. Please add the same in function definition.
this.getList = function (compName, custName) {
var def = $q.defer()
if (allSettings) {
def.resolve(allSettings);
} else {
$http.post('GetAllCurrentSettings', { companyName: compName, customerName: custName })
.then(function (response) {
var response = $.parseJSON(response.data)
allSettings = response;
def.resolve(allSettings);
});
}
return def.promise;
}
You can call the $http.post() in other ways also:
var data = {param:'val1',.....}
$http({
url: "time.php",
method: "POST",
params: data
})

AngularJS/Jasmine: $http.get not working for the test

Something strange is happening in jasmine. My code is working in Angular but when I execute $http.get in jasmin it is not working.
My factory is
app.factory('LocalizationHandler', ['$http', '$q', function ($http, $q) {
var self = this;
var res = {
SetNewCulture: function (culture)
{
console.log("Inside SetNewCulture");
self.culture = culture;
var res = "";
var defer = $q.defer();
$http.get("Scripts/Lib/Factories/Localization/CookinConcepts.json").success(function (response)
{
console.log("estoy dentro");
defer.resolve(response);
return defer.promise;
}).
error(function (e) {
console.log("ERROR");
}).
then(function (response)
{
console.log("OKEY");
self.LocalizationItems = response.data[self.culture];
});
return defer.promise;
}
}
self.LocalizationConstructor = function () {
res.SetNewCulture(res.GetCurrentCulture());
self.LocalizationItems = null;
self.culture = "ca-ES";
};
self.LocalizationConstructor();
return res;
}]);
My test is:
/// <reference path="../../../_references.js" />
describe("Factory - LocalizationHandler", function () {
var lh;
beforeEach(module('appCookIn'));
beforeEach(function () {
inject(function (LocalizationHandler) {
lh = LocalizationHandler;
});
});
it("LocalizationHandler - SetNewCulture", function () {
// Arrange
var expected = "es-ES";
// Act
var result = lh.SetNewCulture("es-ES");
// Assert
expect(result).not.toBe(expected);
});
});
with console.logI see only the next text in the OutPut window: Inside SetNewCulture.
SHOULD THE JSON FILE IN THE TEST PROJECT OR IN THE MAIN PROJECT?
Why in the test the function $http is not working? should geta json file with my culture?

AngularJS/Ionic Service Factory Cache

I'm trying to "cacheify" my angular service factory. I want it to use the cache to hit the URL only the first time the page is loaded. Then when I browse to my detail page (findById) I want to use the cache. Does this make sense?
Below is what I have right now but I can't figure out a solid way to handle this async. My controller is calling into the service.
angular.module('myapp.services', [])
.factory('myservice', function ($http, $q, $cacheFactory) {
var url = '//myurl.com/getawesomeJSON';
return {
findAll: function () {
var $httpDefaultCache = $cacheFactory.get('$http');
var data = $httpDefaultCache.get(url);
if (data == null) {
data = $http.get(url, { cache: true });
}
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
},
findById: function (id) {
var data = angular.fromJson($cacheFactory.get('$http').get(url)[1]);
for (var i = 0; i < data.length; i++) {
if (data[i].Id === parseInt(id)) {
var deferred = $q.defer();
deferred.resolve(data[i]);
return deferred.promise;
}
}
}
}
});
I haven't tested this since you didn't provide a plunker, but the following should set you in the right direction. You need to make use of promise chaining.
angular.module('myapp.services', [])
.factory('myservice', function ($http, $q, $cacheFactory) {
var url = '//myurl.com/getawesomeJSON';
return {
findAll: function () {
var $httpDefaultCache = $cacheFactory.get('$http');
var deferred = $q.defer();
var data = $httpDefaultCache.get(url);
if (!data) {
$http.get(url, { cache: true }).then(function(result){
deferred.resolve(result);
});
} else {
deferred.resolve(data);
}
return deferred.promise;
},
findById: function (id) {
return this.findAll().then(function(data) {
for (var i = 0; i < data.length; i++) {
if (data[i].Id === parseInt(id)) {
return data[i];
}
}
return $q.reject('Not found'); // id not found
});
}
}
});

Resources