Binding a service response in Angular JS - javascript

I am trying to send the http response as a JSON body to an error handler if an error occurs. I am not really sure how to do this as I am a little inexperienced in this area. Here is the relevant code that I have currently:
Controller:
for (var prop in $scope.applicants) {
var applicant = $scope.applicants[prop];
$scope.sendApplicantsToSR(applicant).then(null, $scope.sendATSError.bind(null, applicant));
}
$scope.sendATSError = function (applicant, error) {
return AtsintegrationsService.applicantErrorHandling(applicant.dataset.atsApplicantID);
};
$scope.sendApplicantsToSR = function(applicant) {
return AtsintegrationsService.sendApplicantsToSR(applicant);
};
Service:
srvc.sendApplicantsToSR = function (applicant) {
var applicantURL = {snip};
return $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
url: applicantURL,
data: applicant
});
};
srvc.applicantErrorHandling = function (applicantID, error) {
var url = srvc.url + {snip};
return $http({
method: 'POST',
url: url,
data: { "error_message": error }
});
};
So, ideally, I would like to pass the result of $scope.sendApplicantsToSR to $scope.sendATSError only when an error occurs.

Inside your controller
YourService.getdatafromservice().then(function(SDetails) {
//response from service
console.log(SDetails);
});
Inside your service
return {
getData: getData
};
function getData() {
var req = $http.post('get_school_data.php', {
id: 'id_value',
});
return req.then(handleSuccess, handleError);
function handleSuccess(response) {
response_data = response.data;
return response_data;
}
function handleError(response) {
console.log("Request Err: ");
}
}

Related

Function defined in a service is not a function angularjs

I have a controller Device Controller. I am trying to access a function in service but I am getting an error -
TypeError: DeviceService1.addNewDevice is not a function
at ChildScope.$scope.submitDeviceDtls (CreateDeviceCtrl.js:175)
Here's my code
$scope.submitDeviceDtls = function () {
if ($scope.isNewDevice) {
DeviceService1.addNewDevice($scope.device).then(
function (res) {
console.log(JSON.stringify(res));
// logic
}
}
}
I have a service DeviceService1
function ($http, $q, ApiService, AuthService) {
return {
addNewDevice: function (deviceDtls) {
var deferred = $q.defer();
var payload = new FormData();
payload.append('deviceDtls', new Blob([JSON
.stringify(deviceDtls)], {
type: "application/json"
}));
// payload.append('profilePic', profile_pic);
payload.append('doctorId', AuthService.getDoctorId());
var req = {
method: 'POST',
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity,
responseType: 'arraybuffer',
data: payload
}
ApiService.generic_post('/device/', req).then(
function (res) {
deferred.resolve(res);
}, function (error) {
deferred.reject(error);
}
);
return deferred.promise;
}
return DeviceService1;
Can someone help me? TIA
At your DeviceService1 you are returning firstly an object with the properties you need which includes the function (addnewDevice) you are trying to call but afterwards you return DeviceService1 (return DeviceService) which overrides the first return.
Just remove the following part:
return DeviceService1;

Service method not getting fired using .then

Below is my AngularJs code where I am trying to call TalentPoolService.search() after succussfull ProcessCriteria call, however for some reason it not hitting the TalentPool.Service. What am I doing wrong here?
$scope.Search = function (item, SolrLabel) {
if (item != null) {
console.log('Item: ' + item.Key);
console.log('SolrLabel: ' + SolrLabel);
console.log($localStorage.message);
var pvarrData = new Array();
pvarrData[0] = JSON.stringify($localStorage.message);
pvarrData[1] = item.Key;
pvarrData[2] = SolrLabel;
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(pvarrData),
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
console.log('ProcessCriteria Success fired');
$localStorage.message = response.data;
console.log(response.data);
return response.data;
},
function (response) {
// failed
console.log('facet post error occured!');
}).then(
function () {
TalentPoolService.search().then(function successCallback(response1) {
$scope.talentpoolist = response1.data.model;
$localStorage.message = response1.data.baseCriteria;
console.log('TalentPoolService.search successCallback fired');
setTimeout(function () {
LetterAvatar.transform();
}, 20);
}, function errorCallback(response1) {
$scope.errors = [];
$scope.message = 'Unexpected Error while saving data!!' + response;
})
}
);
}
}
You must return data for chaining to work.
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(pvarrData),
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
console.log('ProcessCriteria Success fired');
$localStorage.message = response.data;
console.log(response.data);
return response.data; // **return here**
},
function(response) {
// failed
console.log('facet post error occured!');
}).then(
function() {
TalentPoolService.search().then(function successCallback(response1) {
$scope.talentpoolist = response1.data.model;
$localStorage.message = response1.data.baseCriteria;
setTimeout(function() {
LetterAvatar.transform();
}, 20);
}, function errorCallback(response1) {
$scope.errors = [];
$scope.message = 'Unexpected Error while saving data!!' + response;
})
}
);
Why because, the next then which you are using expects some data to work on. So, if you don't return it can't. So, must return data.

passing error message from service to controller in angularjs

Controller.js
var vm = this;
vm.admin = {};
vm.add = function () {
API.addAdmin(token, vm.admin)
.then(function (resp) {
vm.hideForm = true;
vm.showButton = true;
Notify.green(resp);
}, function (resp) {
Notify.red(resp);
});
};
API.js
function addAdmin(token, dataObj) {
return Constant.getApiUrl()
.then(function (url) {
$http({
method: 'POST',
url: url + '/client/admin',
headers: {
'Token': token
},
data: dataObj
}).then(handleResp);
function handleResp(resp) {
var responseStatus = (resp.status >= 200 && resp.status < 300) ? 'good' : 'bad';
if (responseStatus === 'good') {
console.log("Success" + resp);
return resp;
} else {
console.log("Failed" + resp);
return resp;
}
}
})
}
If I get a success response in API then i need to connect it to success function in my controller and if i get error message in my API, then i need it to connect it to error function in my controller.How should I evaluate the response status from my API(is either success or error).
I don't want to pass successfn, errorfn from my controller to API(only if there's no alternative).
I need to get the response data from API to controller to show it in Notify message.
Thank You!
In service (assign response values in "originalData"):
angular.module('appname').service('myserviceName', function(yourExistingService){
this.myFunction= function(originalData) {
//for next line to work return promise from your addAdmin method.
var promise = yourExistingService.getResponseFromURL(originalData);
return promise;
}
});
And in your controller :
var promise = myserviceName.myFunction($scope.originalData);
promise.$promise.then(function() {
console.log($scope.originalData);
});
And then you can check you "originalData" and write code according to your need.For more detail you can have a look on this http://andyshora.com/promises-angularjs-explained-as-cartoon.html.

AngularJs conversion of service

the title to this is a bit ambiguous I know, but I couldn't think of what to call it :)
Hopefully this description will help.
I have this current "service" which looks like this:
.factory('MoltinApi', ['$cookies', '$q', '$resource', '$http', 'moltin_options', function ($cookies, $q, $resource, $http, options) {
var api = $resource(options.url + options.version + '/:path', {
path: '#path'
});
var authenticate = function () {
if (!options.publicKey)
return;
var deferred = $q.defer();
//var authData = angular.fromJson($cookies.authData);
var authData = false;
if (!authData) {
console.log('from api');
var request = {
method: 'POST',
url: options.url + 'oauth/access_token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: "grant_type=implicit&client_id=" + options.publicKey
};
deferred.resolve($http(request).success(function (response) {
$cookies.authData = angular.toJson(response);
setHeaders(response.access_token);
}));
} else {
console.log('from cookie');
deferred.resolve(setHeaders(authData.access_token));
}
return deferred.promise;
};
var setHeaders = function (token) {
$http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}
return authenticate().then(function (response) {
return api;
});
}]);
As you can see, when we authenticate, we then return the api function.
I have decided that using $resource isn't working as good as I had hoped, so I have now tried to change the service to this:
.factory('MoltinApi', ['$cookies', '$q', '$http', 'moltin_options', function ($cookies, $q, $resource, $http, options) {
// Private variables
var headers;
// Build request call
var buildRequest = function (path, method, data) {
var request = {
method: method,
url: options.url + options.version + path,
data: data
};
console.log(headers);
if (headers) {
angular.extend(request, headers)
}
return $http.request(request);
}
// GET
var $get = function (path) {
var request = buildRequest(path, 'GET')
return $http.request(request);
}
// POST
var $post = function (path, data) {
var request = buildRequest(path, 'POST', data)
return $http.request(request);
}
// PUT
var $update = function (path, data) {
var request = buildRequest(path, 'PUT', data)
return $http.request(request);
}
// DELETE
var $delete = function (path) {
var request = buildRequest(path, 'DELETE')
return $http.request(request);
}
// authentication
var authenticate = function () {
if (!options.publicKey)
return;
var deferred = $q.defer();
//var authData = angular.fromJson($cookies.authData);
var authData = false;
if (!authData) {
console.log('from api');
var request = {
method: 'POST',
url: options.url + 'oauth/access_token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: 'grant_type=implicit&client_id=' + options.publicKey
};
deferred.resolve($http(request).success(function (response) {
$cookies.authData = angular.toJson(response);
headers = { headers: { 'Authorization': 'Bearer ' + response.access_token } }
}));
} else {
console.log('from cookie');
deferred.resolve(
headers = { headers: { 'Authorization': 'Bearer ' + authData.access_token } }
);
}
return deferred.promise;
};
return authenticate().then(function (response) {
// Need to return $post, $get, $update and $delete
});
}]);
But I am at a loss on how to return my methods after we have athenticated...
Can someone help me out?
you need to wrap all the methods into an object, and return the object. Try:
var api = {};
...
api.$get = function (path) {
...
api.$post = function (path, data) {
...
//etc
return authenticate().then(function (response) {
return api;
});

How to call ajax from service in AngularJS?

I have Employee controller which is having property Id, Name , Specification. I have made one Employee service which is having ajax call and get employee list. But every time getting '' in User.
When i debug the code i found that it call success first and then it goes for Ajax call.
When i do ajax call without service it works fine.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.Users = '';
this.errors = '';
this.SearchEmployee = function () {
// Ajax call
$http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
var onSuccess = function (response) {
this.userUsers = response.data;
this.errors = '';
};
var onError = function (reason) {
this.userUsers = reason;
this.errors = "Error in retrieving data.";
};
return this.Users;
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.Id = '';
this.name = '';
this.expertise = '';
$scope.repoSortOrder = 'id';
$scope.filterField = '';
// Call to service
this.GetAllEmployee = function () {
// Initiates the AJAX call
$scope.User = EmployeeSer.SearchEmployee();
// Returns the promise - Contains result once request completes
return true;
};
this.AddEmployee = function () {
var empData = {
Id: $("#txtId").val(),
Name: $("#txtName").val(),
Expertise: $("#expertise").val()
};
$http({
method: 'POST',
url: '/Home/Create',
params: JSON.stringify(empData),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
// Returns the promise - Contains result once request completes
return true;
};
var onSuccess = function (response) {
$scope.user = response.data;
$scope.error = '';
};
var onError = function (reason) {
$scope.error = "Error in retrieving data.";
};
}]);
It's because you are returning the users before the data is fetched from the server. Also it doesn't seem like you are assigning them correctly.
Here are two ways to solve the problem:
Firstly. You bind your controller user-data to the user-data in the service.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.Users = '';
this.errors = '';
$http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
var onSuccess = function (response) {
this.Users = response.data;
this.errors = '';
};
var onError = function (reason) {
this.users = null;
this.errors = "Error in retrieving data.";
};
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.users = EmployeeSer.users;
EmployeeSer.SearchEmployee();
}]);
And the second way would be to return the promise in the service and unwrap it in the controller.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.SearchEmployee = function () {
return $http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.GetAllEmployee = function () {
EmployeeSer.SearchEmployee()
.then(onSuccess, onError)
};
var onSuccess = function (response) {
$scope.user = response.data;
$scope.error = '';
};
var onError = function (reason) {
$scope.error = "Error in retrieving data.";
};
}]);
OFF TOPIC
You should probably consider using ngModel instead of jQuery to get you data to the controller.
Not like this:
var empData = {
Id: $("#txtId").val(),
Name: $("#txtName").val(),
Expertise: $("#expertise").val()
};
// Here serverRequest is my service to make requests to the server
serverRequest.postReq = function(url, data, sucessCallback, errorCallback){
$http({
method: 'POST',
url: urlToBeUsed,
data:data,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(data, status, headers, config) {
sucessCallback(data);
})
.error(function(data, status, headers, config){
errorCallback(data);
})
}
// In the controller
serverRequest.postReq('urlToBeCalled', dataToBeSent, scope.successCb, scope.errorCb);
scope.successCb = function(data){
// functionality to be done
}
scope.errorCb = function(data){
// functionality to be done
}
Try it this way your problem might be solved
Promise must be unwrapped in your controller if you want to use it

Categories

Resources