How to send an object and array through Angularjs service - angularjs

I am trying to send an object and array in the same time to an API, but i got an error
This is the object (from input boxes)
var vacation = {
Vac_Main_Key: $scope.vackey, Vac_Main_Code: $scope.code, Gender_Type: $scope.gen, CareeService_Flag: $scope.career, Vac_Duration: $scope.vduration,
Duration_Flag: $scope.vflag}
This is the array (from multiple check boxes)
$scope.selectedcontract = function (con)
{
if (con.details == true) {
$scope.vacationcontracts.push({ VacMKey: $scope.vackey, WType: con.sys_key });
console.log($scope.vacationcontracts);
}
else if (con.details == false) {
$scope.vacationcontracts.splice(con, 1);
}
}
The save button
var promisePost = vacationsetupSrv.save(vacation, $scope.vacationcontracts);
promisePost.then(function () {}
The angularjs service:
var vacationsetup = angular.module("vacationsetup", [])
.service("vacationsetupSrv", function ($http) {
var urlBase = "/VacationSetupAPI/api";
this.save = function (url, vacation,vacationcontracts) {
return $http({
method: "POST",
url: urlBase + '/' + url,
data: vacation, vacationcontracts,
async: false,
})
};
i got this error http://localhost/VacationSetupAPI/api/[object%20Object]
Any help, Thanks in advance

Try
this.save = function (vacation,vacationcontracts) {
You are sending object as 1st argument and then assigning it to the url as string, that’s wrong.
vacationsetupSrv.save(vacation, $scope.vacationcontracts);
OR
Try
vacationsetupSrv.save(“”,vacation, $scope.vacationcontracts);

Related

How to send ajax post array to mvc controller in vb.net

My javascript code;
<script>
$(document).on('click', '.Send', function () {
var a = [];
$(".k_sure").each(function () {
var a_array= a.push($(this).val());
});
var b= [];
$(".k_sure").each(function () {
var b_array= a.push($(this).val());
});
var DataDiscount= { time: a_array, ind: b_array};
$.ajax({
type: "POST",
url: "/admin/pan/discount",
data: DataDiscount,
traditional: true,
dataType: 'html',
success: function (c) { }
error: function () { }
});
});
</script>
My array;
DataDiscount:{time:["5","8","9"], ind:["%10","%15","%20"]}
my controller code;
Function discount(time As String, ind As String) As String
Dim x_add As New Discounts
If x_add IsNot Nothing Then
x_add.time = time
x_add.ind = ind
db.Discounts.Add(x_add)
db.SaveChanges()
Return "Success"
Else
Return "Err"
End If
Return ""
End Function
but only records the first data (5 and %10)
how to fix Controller code. My english is bad so sorry
I don't know about your controller settings but you should send your data as a JSON object.
Try to JSON.stringify your data:
var DataDiscount= JSON.stringify({ time: a_array, ind: b_array});

how to handle multiple delete and displaying 1 message using delete service in angular JS

When i check all lists in table, and press delete button, A DELETE SERVICE will be called.(Using AngularJS)
Problem is, i am using a loop, and on successful delete and unsuccessful delete, i am getting alert multiple times.(No. of selection times)
And its not working properly, if place it out of loop because its Async Task.
Here is the code,
This is a controller which initiates a service.
$scope.confirmAction = function() {
var costsToDelete = [];
angular.forEach($scope.objects, function(cost) {
if (cost.selected == true) {
costsToDelete.push(cost);
}
});
$scope.deleted = true;
//need to put confirmation dialog here.
//URL: specific to timesheet deletion. it will be prefixed with constant url
var delRequestUrl = URLs.costsUrl + '/';
deleteService.deleteRecord($scope.objects, costsToDelete, delRequestUrl);
};
This is a service.
.service('deleteService', ['dataService', 'Constant.urls', 'Constants','$q','alerts',function(dataService, URLs, Constants, $q, alerts) {
var deleteService = {};
deleteService.deleteRecord = function(records, listOfRecordsToDelete, url) {
while (listOfRecordsToDelete.length > 0) {
var recordToBeDeleted = listOfRecordsToDelete.pop();
var index = listOfRecordsToDelete.indexOf(recordToBeDeleted);
var delRequestUrl = url + recordToBeDeleted.id;
var result = dataService.deleteObject(delRequestUrl);
result.success(function(data) {
Alert('success');
records.splice(index, 1);
});
result.error(function(data, status, headers, config) {
dataService.handleError(status,data);
Alert('error');
});
}
};
return deleteService; }])
I need a result like: Alert should display only once.
If all items are successfully deleted, then success or failure message.
Why dont you just create a boolean bit var status= false;//default value to true inside success callback handler and false inside error callback handler,
so once all calls are complete based on this bit you can alert success or failure
Angular JS Code:
.service('deleteService', ['dataService', 'Constant.urls', 'Constants','$q','alerts',function(dataService, URLs, Constants, $q, alerts) {
var statusBit = false; // status tracker
var deleteService = {};
deleteService.deleteRecord = function(records, listOfRecordsToDelete, url) {
while (listOfRecordsToDelete.length > 0) {
var recordToBeDeleted = listOfRecordsToDelete.pop();
var index = listOfRecordsToDelete.indexOf(recordToBeDeleted);
var delRequestUrl = url + recordToBeDeleted.id;
var result = dataService.deleteObject(delRequestUrl);
result.success(function(data) {
// Alert('success');
statusBit = true;
records.splice(index, 1);
});
result.error(function(data, status, headers, config) {
dataService.handleError(status,data);
//Alert('error');
statusBit = false;
});
if(statusBit){
Alert('success'); //console.log('successfully deleted');
}
else {
Alert('error'); // console.log('error while deleting');
}
};
return deleteService; }])
.service('deleteService', ['dataService', 'Constant.urls', 'Constants','$q','alerts',function(dataService, URLs, Constants, $q, alerts) {
var deleteService = {};
deleteService.deleteRecord = function(records, listOfRecordsToDelete, url) {
var overallResult = true;
while (listOfRecordsToDelete.length > 0) {
var recordToBeDeleted = listOfRecordsToDelete.pop();
var index = listOfRecordsToDelete.indexOf(recordToBeDeleted);
var delRequestUrl = url + recordToBeDeleted.id;
var result = dataService.deleteObject(delRequestUrl);
result.success(function(data) {
records.splice(index, 1);
});
result.error(function(data, status, headers, config) {
dataService.handleError(status,data);
overallResult = false ;
});
}
};
return deleteService; }])

Second jsonp http get request - using $q gives 404 error despite GET showing 200

I've found a couple of similar posts to this, but the answers (which boil down to putting callback=JSONP_CALLBACK into the get request) aren't working for me. Using that in the request generates an immediate 404 error, while using callback=angular.callbacks._0 at least lets the first request return a successful response. The problem is that using the very same request function with the very same params a second time to refresh the data or get the next 20 objects, returns a 404 error even though the actual get returns a 200 and the data can be seen in chrome tools.
I'm, new to using $q deferred promises, so I'm hoping that the issue has something to do with that not allowing enough time for a response before executing the reject. I'm attaching the code, which involves the Yelp API as did the other couple of posts I found on this issue. The most closely related is: (Subsequent JSONP requests give status 404 despite GET status 200), but there's another which uses the same callback string I'm using (Yelp API and AngularJS).
This particular project is for an ionic mobile app that gets coffee shops based on users geolocation.
Here's the code for the service (secret stuff removed):
var app = angular.module('caffeine.services', []);
app.service("YelpService", function ($q, $http, $cordovaGeolocation, $ionicPopup) {
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
};
var method = 'GET';
var url = 'http://api.yelp.com/v2/search';
var consumerSecret = ''; //Consumer Secret
var tokenSecret = ''; //Token Secret
var self = {
'page': 1,
'isLoading': false,
'hasMore': true,
'results': [],
'ranStr': randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'),
'timeStamp':new Date().getTime(),
'lat': 51.544440,
'lon': -0.022974,
'term': 'coffee',
'oauthConKey': '', //Consumer Key
'oauthToken': '', //Token
'oauthSigMeth': 'HMAC-SHA1',
'refresh': function () {
self.page = 1;
self.isLoading = false;
self.hasMore = true;
self.results = [];
return self.load();
},
'next': function () {
self.page += 1;
return self.load();
},
'load': function () {
self.isLoading = true;
var deferred = $q.defer();
ionic.Platform.ready(function() {
$cordovaGeolocation
.getCurrentPosition({timeout:10000, enableHighAccuracy:false})
.then(function(position){
self.lat = position.coords.latitude;
self.lon = position.coords.longitude;
console.log('latlong = '+self.lat+','+self.lon);
var params = {
callback: 'angular.callbacks._0',
page: self.page,
ll: self.lat+','+self.lon,
term: self.term,
oauth_consumer_key: self.oauthConKey, //Consumer Key
oauth_token: self.oauthToken, //Token
oauth_signature_method: self.oauthSigMeth,
oauth_timestamp: self.timeStamp,
//new Date().getTime(),
oauth_nonce: self.ranStr
};
var signature = oauthSignature.generate(method, url, params, consumerSecret, tokenSecret, { encodeSignature: false});
params['oauth_signature'] = signature;
console.log('url ='+url);
console.log('params.ll = '+params.ll);
$http.jsonp(url, {params: params}).success(function (callback) {
self.isLoading = false;
console.log(callback.businesses);
if (callback.businesses.length == 0) {
self.hasMore = false;
} else {
angular.forEach(callback.businesses, function (business) {
self.results.push(business);
});
}
self.isLoading = false;
deferred.resolve(callback.businesses);
})
.error( function (callback, status, headers, config) {
self.isLoading = false;
console.error('data not received');
console.error('data: '+callback);
console.error('status: '+status);
console.error('headers: '+headers);
console.error('congig: '+config);
deferred.reject(callback);
});
}, function(err) {
console.error('Error getting position');
console.error(err);
$ionicPopup.alert({
'title': 'Please turn on geolocation',
'template': 'It looks like you have geolocation turned off. Please turn on geolocation in your app settings to use this app.'
});
})
});
return deferred.promise;
}
};
self.load();
return self;
});

Angularjs $http my second then before first then is done.

I am not sure what I am doing wrong here, but the Report.xls gets downloaded before report.students gets updated.
How can I make it wait for report.students to be updated before Report.xls get downloaded?
Here is my code
`data service function
function getStudentsForExcel() {
var filter = studentFilter;
filter.data.perPage = StudentsModel.data.countTotal;
return $http.post(url + "/summeries", filter.data)
.then(onStudentSummeries)
.catch(onError);
function onStudentSummeries(response) {
return response.data;
}
}`
This function in my controller
`
function tocsv() {
studentData.getStudentsForExcel().then(function(data) {
report.students = data;
}).then(function() {
var blob = new Blob([document.getElementById('tableReport').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Report.xls");
});
}`

AngularJS scope refresh on post to API through restangular

I have a controller which loads data via Restangular like so:
var oneTopic = Restangular.one('topics', topic.id);
oneTopic.get({}, {"Authorization" : localStorageService.get('***')}).then(function(topic) {
topic.getList('comments', {}, {"Authorization" : localStorageService.get('***')}).then(function(comments){
$scope.comments = comments;
//console.log($scope.comments);
});
});
And then a function which posts a new comment and one that deletes a comment.
$scope.delComment = function(comment_id, author_id){
var comment = Restangular.one('comments', comment_id);
comment.remove({author_id: author_id}, {"Authorization" : localStorageService.get('***')}).then(function(){
// need to perform refresh here
});
};
$scope.postComment = function(mood) {
$scope.commentData.mood = mood;
comments.post($scope.commentData, {}, {"Authorization" : localStorageService.get('***')}).then(function(response){
// need to perform refresh here
}, function(response){
$scope.error = response.data.message;
})
};
How would I refresh the comments scope without reloading the page? The data is being populated in the HTML with an
<div ng-repeat="comment in comments">
Modify the existing array referenced by $scope.comments and the data binding will take care of it.
For example:
$scope.delComment = function(comment_id, author_id) {
var comment = Restangular.one('comments', comment_id);
comment.remove({ author_id: author_id }, { "Authorization": localStorageService.get('***')
}).then(function() {
// Some remove-from-array implementation, for example:
var c = $scope.comments;
for(var i = 0, l = c.length; i < l; i++) {
if (c[i].comment_id === comment_id) {
c = c.splice(i, 1);
break;
}
}
});
};

Resources