AngularJS $http.delete not working in Azure App Service - angularjs

A follow-up on a similar question I posted yesterday. I am trying to delete data from a table in Azure App service. This is my function in my Angular file.
function delName(user) {
//$scope.categories.push(user);
alert("about to delete. Action cannot be undone. Continue?")
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people', user, config)
.then(function (res) {
$scope.getNames();
});
}
Then I added an HTML button:
<button id="btn-del-evangelist" class="btn btn-default btn" ng-click="delName(user);">Delete User</button>
This is the value of my headers variable:
var config = {
headers: {
'Access-Control-Allow-Origin':'*',
'ZUMO-API-VERSION': '2.0.0'
}
};
But when I tried to run it, the console returns the following error:
which states that the header for ZUMO-API-VERSION must be specified.
Below is my code for GET and POST
GET:
function getNames() {
$http.get('https://test-evangelists-1.azurewebsites.net/tables/people', config)
.then(function (res) {
console.log(res);
$scope.people = res.data;
});
}
POST
function addName(user){
//$scope.categories.push(user);
alert("about to post!")
$http.post('https://test-evangelists-1.azurewebsites.net/tables/people', user, config)
.then(function (res) {
$scope.getNames();
});
}
Since I have already specified the header in my variable, I wonder what can be wrong here. Any help will be appreciated.
UPDATE:
I figured out that the Id must be appended to the URL before I can perform delete. However, I need to run a GET to retrieve the ID given the parameters but I am still encountering errors when getting the ID.
This is now my Delete function
function delName(user) {
alert("About to delete. Action cannot be undone. Continue?")
var retrievedId = "";
$http.get('https://test-evangelists-1.azurewebsites.net/tables/people', {
params: { name: user.name, location: user.location },
headers: { 'Access-Control-Allow-Origin': '*', 'ZUMO-API-VERSION': '2.0.0' }
})
.then(function (res) {
retrievedId = res.id;
alert(retrievedId);
});
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people/' + retrievedId, config)
.then(function (res) {
$scope.getNames();
});
}
Does anyone know what is wrong in the GET command when getting the ID?
UPDATE 2: I have written instead an Web Method (asmx) that will connect to SQL server to retrieve the ID passing the needed parameters. The ID will be returned as a string literal but in JSON format. Then I called JSON.parse to parse the string into JSON object then assigned the ID to a variable to which I appended in the URL. –
This is now my Delete function after I have written the Web Method.
function delName(user) {
var confirmres = confirm("You are about to delete this record. Action cannot be undone. Continue?");
var retrievedId = "";
if (confirmres == true) {
//get the ID via web service
$http.get('\\angular\\EvangelistsWebService.asmx/GetId', {
params: { name: user.name, location: user.location },
headers: { 'Access-Control-Allow-Origin': '*', 'ZUMO-API-VERSION': '2.0.0' },
dataType: "json",
contentType: "application/json; charset=utf-8"
})
.then(function (res) {
$scope.retData = res.data;
var obj = JSON.parse($scope.retData);
angular.forEach(obj, function (item) {
if (item.length == 0)
alert('No data found');
else {
//perform delete after getting the ID and append it to url
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people/' + item.id, config)
.then(function (res) {
$scope.getNames();
});
alert(item.id + ' deleted');
}
});
});
}
}
That is one way that I have learned on how to call HTTP DELETE on AngularJS. But I don't know if that is the optimal one. In any case, that works for me, unless there will be other suggestions.

$http.delete only has one parameter (config), not two (data, config).
Delete API
delete(url, [config]);
vs.
Post API
post(url, data, [config]);
To your updated problem:
To delete an item from your table, it appears the correct url is:
/tables/tablename/:id
Note the : before id.

Related

PUT Request with AngularJS and Express

When I'm performing a put request and console.log(response) of the request I only get a JSON Object like {"res":1} instead of getting the whole json object with its changes in order to update him in a database.
Controller :
$scope.doneEdit = function (components) {
console.log(components);
components.editing = false;
if (components.editing === false) {
$http.put('/propt/' + components._id).then(function (response) {
console.log(response.data);
});
}
}
Express
app.put('/propt/:id', function(req,res) {
console.log(req.body);
testDb.update({_id:req.params.id}, req.body, {}, function(err, numReplaced){
res.statusCode = 200;
res.send(req.body);
})
})
You should pass the data you want to send as a second parameter to put method:
$http.put('/propt/' + components._id, {someValue:components.someValue})
You can find the documentation here: https://docs.angularjs.org/api/ng/service/$http#put

data is undefined in transformRequest using $resource

I'm working on a small project with MEAN in order to get started with it. I've been following the tutorial on thinkster.io (with some minor modifications made by me) and so far I've obtained good results. I've tested the API routes with Postman and everything is working. Problem is, for some reason (keep in mind that I'm new to NodeJS), it only accepts requests with Content-type: x-www-form-urlencoded.
The solution I've come across several times is to change the headers in the options parameter of the $resource. This is the code I have
register: function(user){
var deferred = $q.defer();
var UserResource = $resource('/api/users/register', {}, {
save: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function (data, headersGetter) {
console.log(data); // data is undefined ??
var str = [];
for (var d in data)
str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&");
}
}
});
UserResource.save(function(user){
this.saveToken(user.token);
deferred.resolve(user);
}, function(user){
deferred.reject(user);
});
return deferred.promise;
}
The register function is declared on an angular service. Problem is that the backend is sending me an error because the req.body object is empty. This is due to the fact that the transformRequest method is not executing correctly. Doing a little debugging I found that the 'data' parameter is undefined.
This is the code in the backend
router.post('/register', function(req, res, next){
if(!req.body.username || !req.body.password){
console.log(req.body.username);
return res.status(400).json({message: 'Por favor llene todos los campos'});
}
var user = new User();
user.username = req.body.username;
user.fullname = req.body.fullname;
user.setPassword(req.body.password);
user.save(function (err){
if(err){ return next(err); }
return res.json({token: user.generateJWT()})
});
});
Any ideas would be appreciated. Thanks in advance
You should pass user data in 1st parameter of save method(that will pass through the request body), there after you can place successCallback & errorCallback
UserResource.save(user, function(user){
this.saveToken(user.token);
deferred.resolve(user);
}, function(user){
deferred.reject(user);
});
Checkout this article

ng-repeat is not updating my mode data

I am new to angularJS. I am using ionic framework for android application development. In my project I am calling webservice and getting its response and attaching that response to scope variable to get data on the view. First time webservice called and updates the view as expected but when I call the service again that is not updating my data. It seems as ng-repeat is not working due to some reference loosing problem. But I am not able to find out the solution of that. Although I have tried different solution via using apply() as was mentioned in one of the stack overflow posts. Below is the code of attaching web-service response to the scope variable.
$http(req).then(function (response) {
if (response.data.IsSuccess) {
console.log("data = " + JSON.stringify(response.data));
console.log('Response is '+response.data.IsSuccess);
$scope.companies = response.data.Response.Companies;
}
and below is the line of code using to update the view
<div class="col col-100" ng-repeat="company in companies">
any help or advice
Below is the login code that is calling webservice to update my data
function callLogInService(userName, password){
console.log("user name is " +userName);
console.log("password is " + password);
var req = {
method: 'POST',
url: ApiUrl + '/api/User/LoginUser',
headers: {
'Content-Type': 'application/json'
},
data: {
Email: userName,
Password: password
}
}
$ionicLoading.show({
template: 'Signing in...'
});
$http(req).then(function (response) {
if (response.data.IsSuccess) {
console.log("data = " + JSON.stringify(response.data));
console.log('Response is '+response.data.IsSuccess);
var userID = response.data.Response.AppUserId;
var userName = response.data.Response.AppUserName;
setUserName(userName);
setUserId(userID);
$rootScope.appUserName;
var userIdFromSession = getUserID;
if(undefined == $rootScope.companyIdForSubscription
|| $rootScope.companyIdForSubscription == 0){
console.log("id is undefined for subscription");
} else {
console.log("company subscription id is " + $rootScope.companyIdForSubscription);
$scope.subscribe($rootScope.companyIdForSubscription);
}
$scope.close();
$scope.setVisibilityOdSideMenuIcons();
$scope.getAllCompanies();
}
else {
showErrorAlertDialogue(response.data.ErrorMessage);
}
}, function (reason) {
console.log('reason is ' + reason.data);
$log.info('reasonf log is' + reason) ;
showErrorAlertDialogue("Please check your internet connection.");
}).finally(function () {
console.log("finally is called");
$ionicLoading.hide();
$ionicPopup.close()
});
}
$scope.getAllCompanies(); this line is calling service again

AngularJS $http returns status code 0 and data as null in SharePoint 2013

I am facing an issue when inserting records in to multiple lists using rest api with http calls in SharePoint 2013.
I have written common method mentioned below which will take input params as data and url.
var postRequest = function (data, url) {
var deferred = $q.defer();
$http({
url: baseUrl + url,
method: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"If-Match": "*"
},
data: JSON.stringify(data)
}).success(function (result) {
alert(result.d.Id);
deferred.resolve(result.d.Id);
}).error(function (result, status) {
alert(status + result);
deferred.reject(status);
});
return deferred.promise;
};
Using the above code I am inserting data in to list A, once record has been inserted in to list a, With item id of I am inserting record in list b with additional fields and list C.
I am calling above common method which is mentioned as below.
$scope.submitData = function (LSSDeal, lssIds, amIds) {
var submitDataPromise = lssDealService.submitLSS(LSSDeal, lssIds, amIds);
submitDataPromise.then(function (transactionResponse) {
var transactionId = transactionResponse;
$scope.AddtoPaymentList(LSSDeal, transactionId);
$scope.AddToHistory(LSSDeal, transactionId);
}, function (error) {
alert("error in submitting transaction data" + error);
});
};
I am able to get transaction id for first request which will insert record in list A.After getting ID I am calling remaining two methods.
$scope.AddtoPaymentList = function (LSSDeal, transactionId) {
var paymentlistPromise = lssDealService.saveToPaymentList(LSSDeal, transactionId);
paymentlistPromise.then(function (paymentlistResponse) {
var paymentId = paymentlistResponse;
alert("LSS Deal has been Added to payment list with transaction Id:" + transactionId);
}, function (error) {
alert("error in inserting payment list data" + error);
});
};
$scope.AddToHistory = function (LSSDeal, parentListId) {
var historyPromise = lssDealService.saveToHistory(LSSDeal, parentListId);
historyPromise.then(function (historyResponse) {
var historyId = historyResponse;
alert("LSS Deal has been Added to history with history Id:" + historyResponse);
}, function (error) {
alert("error in inserting history data" + error);
});
};
For remaining two methods I am always getting error message as status zero and data null.
Simply for second request on wards its going error block but records are inserting successfully.
But when I am debugging getting success messages. Please guide me.
Thanks in advance.
References: http://www.codeproject.com/Articles/1002526/SharePoint-and-Angularjs

Angular.js delete resource with parameter

My rest api accpets DELETE requests to the following url
/api/users/{slug}
So by sending delete to a specified user (slug) the user would be deleted. here is the service code:
angular.module('UserService',['ngResource']).factory('User', function($resource){
var User = $resource('/api/users/:id1/:action/:id2', //add param to the url
{},
{
delete_user: {
method: 'DELETE',
params: {
id1:"#id"
}
},
update: {
method: 'PUT',
params: {
id1:"#id"
}
}
});
return User;
});
I call the delete function via
user.$delete_user({id:user.id}, function(){}, function(response){});
However the request seems to be send to the wrong url.
/api/users?id=4
So the parameter is actually missing, as a result I get a 405 Method not allowed. Is there any chance to send the delete request in the style of my api?
params is an object of default request parameteres in your actions. If you want url parameters you have to specify them in the second parameter like this:
angular.module('UserService',['ngResource']).factory('User', function($resource){
var User = $resource('/api/users/:id1/:action/:id2', //add param to the url
{id1:'#id'},
{
delete_user: {
method: 'DELETE'
}
});
return User;
});
this works with either:
// user has id
user.$delete_user(function(){
//success
},function(){
// error
});
or
var data = {id:'id_from_data'};
User.delete_user({},data);
or
var params = {id1:'id1_from_params'};
User.delete_user(params);
I've made a plnkr-example - you have to open your console to verify that the DELETE requests are correct.
See parameterDefaults in the Angular resource documentation.
I had this problem for a while I was using a service to add / delete / update categories. While passing in params for get it worked fine but then when deleting it was giving me a ?id=1234 instead of api/resource/1234
I got around this by making the default param a string.
///Controller
Service.delete({categoryId:id}, function(resp){
console.log(resp)//whatever logic you want in here
});
//SERVICES
$resource('api/resource/:categoryId', {"categoryId":"#categoryId"}, {
query:{method:"GET"},
delete:{method:"DELETE"},
});
Should work and the resulting url will be, originally I had categoryId in the default params as a variable name.
api/resource/1234 etc
Just omit the '#' in the parameter
.factory('reportFactory', ['$resource', 'baseUrl', function ($resource, baseUrl) {
return $resource(baseUrl + '/keys/:id', {}, {
delete: { method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
params: {id: 'id'} }
})
}]);
this will give you:
http://localhost:8080/reports/api/keys/b8a8a8e39a8f55da94fdbe6c
without the question mark
If you want to delete a model, there's no need to add params (params does not work for DELETE anyway):
$resource('/users/:id').delete({id: user.id}, function(res) {
...
})
or
$resource('/users/:role/:id').delete({role: 'visitor', id: user.id});
I'm not sure if it's a bug of ngResource.

Resources