I need to post data to a SharePoint list, and I want to clean up my code by using
a resource factory, until now I have posted data like this:
this.save = function(data) {
data["__metadata"] = { "type": getItemTypeForListName('ListName') };
var restQueryUrl = appweburl + "/_api/lists/getByTitle('ListName')/items";
$.ajax({
url: restQueryUrl,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
},
data: JSON.stringify(data),
success: function (data) {
console.log(data);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
};
And so far my resource factory looks like this:
myApp.factory('Entry', function($resource) {
return $resource(appweburl + "/_api/lists/getByTitle('ListName')/items", {}, {
get: {
method: 'GET',
headers: { "Accept": "application/json; odata=verbose" },
url: appweburl + "/_api/lists/getByTitle('ListName')/items?$select=Id,Title,Description&$filter=ID eq :ID"
},
query: {
method: 'GET',
headers: { "Accept": "application/json; odata=verbose" },
url: appweburl + "/_api/lists/getByTitle('ListName')/items?$select=Id,Title,Description"
}
})
});
How can I 'convert' my save function to a resource method?
Okey, so I was easier than I thought, what I had to do was run the function 'getItemTypeForListName' before calling the save function, this adds the metadata needed to save to sharepoint. And in my resource factory add this:
save: {
method: 'POST',
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
}
}
And then in my controller call it like this:
$scope.test = new Entry();
$scope.test.Title = 'testTitle';
// function to set metadata
$scope.test["__metadata"] = { "type": getItemTypeForListName('ListName') };
Entry.save($scope.test);
Related
How can I pass mutipul parameters from angularjs -to WebAPi My Api as its Required two parameters
public IHttpActionResult GetData(int pagesize,int Totalpages){---}
angularctrls.js
function GetData() {
var PageDetails={
'currentpage': $scope.currentPage,
'pagesize':$scope.pagesize
}
HomeFactory.GetDat(PageDetails).then(function () {
})
}
Factory.js
EmployeeServiceFactory.GetDat = function (PageDetails) {
return $http({
url:WebAPi+'Home/GetData/',
method: 'GET',
data: PageDetails,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
}
Getting Error as
Failed to load http://localhost:3084/Home/GetData/%7B%22currentpage%22:1,%22pagesize%22:5%7D: No 'Access-Control-Allow-Origin' header is present on the requested resource
try params instead of data like below:
EmployeeServiceFactory.GetDat = function (PageDetails) {
return $http({
url:WebAPi+'Home/GetData/',
method: 'GET',
params: PageDetails,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
}
I think you can put data as an object.
EmployeeServiceFactory.GetDat = function (PageDetails) {
return $http({
url:WebAPi+'Home/GetData/'+PageDetails,
method: 'GET',
data: {page_details:
PageDetails, foo: 'bar'}, headers: { 'Content-Type': 'application/x-www-form-urlencoded'
}
})
}
I am trying to send array subjectAverage to nodejs route. I am using express route, its showing unidentified when trying to print on console.
var app = angular.module("myapp", [])
app.controller("ListController2", ['$scope','getAverage','$http',function($scope, getAverage,$http) {
$scope.subjectAverages = [{
'subjectName': '',
'yearSem': '',
'studentsAppeared': '',
'studentsPassed':'',
'percentage':'',
'average':'',
'facultyComment':''
}];
$scope.save=function(){
var data =angular.toJson($scope.subjectAverages)
var objectToSerialize={'object':data};
$http({
url: 'app',
method: "POST",
data: $.param(objectToSerialize),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data){
alert("done");
});
}
router.post('/app',function(res,req){
console.log(req.body);
});
Please guide.
Try this :
$scope.save=function(){
var data = {object : $scope.subjectAverages};
$http({
url: '/app',
method: "POST",
data: data,
headers: {
'Content-Type': 'application/json'
}
}).then(function(data){ //.success is deprecated,so use .then
alert("done");
})
.catch(function(err){//using .catch instead of .error as it is deprecated
console.log("Error in request =>", err)
});
i am new in programming and angular.
i have the data like this in my controller
temanService.create({
Userid: $scope.datateman.userid,
Address: $scope.datateman.address,
Employeeid: $scope.datateman.employeeid,
Email: $scope.datateman.email,
Phoneno: $scope.datateman.phoneno,
Password: $scope.datateman.password,
Division: $scope.datateman.division,
Leavebalance: $scope.datateman.leavebalance
}).success(function(data) {
$scope.showAlert({
title: "Information",
message: "Data Telah Tersimpan"
});
});
and this is my service for http.request
angular.module('starter.services', [])
.factory('temanService', function($http) {
var baseUrl = 'http://localhost:60820/MobileBootcamp.svc/';
return {
create: function(datateman) {
return $http.post(baseUrl + 'insert?method=insertuser',
datateman, // <--- what to insert here
{
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
},
update: function(datateman) {
return $http.post(baseUrl + 'update.php', datateman, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
}
});
},
delete: function(id) {
return $http.get(baseUrl + 'delete.php?id=' + id);
}
};
});
and this is example of the correct parameter for insert
{
"Value": "userid|address|employeeid|email|phoneno|password|division|leavebalanc"
}
My question is,
How to put data to the http request post method?
i wanted to make like this
method: 'POST',
url: 'http://110.35.82.163:9090/MobileBootcamp.svc/insert? method=insertnews',
crossDomain: true,
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: { "Value": userID + "|" + $scope.title + "|" + $scope.posttag + "|" + $scope.content }
Try this
var data = {
Userid: $scope.datateman.userid,
Address: $scope.datateman.address,
Employeeid: $scope.datateman.employeeid,
Email: $scope.datateman.email,
Phoneno: $scope.datateman.phoneno,
Password: $scope.datateman.password,
Division: $scope.datateman.division,
Leavebalance: $scope.datateman.leavebalance
};
var dataCollection = [];
for(var item in data){
if(data.hasOwnProperty(item)){
dataCollection.push(data[item]);
}
}
var DTO = {
Value: dataCollection.join('|');
};
//do not use success. its obsolete
temanService.create(DTO).then(function(response){
},function(response){
//error
});
Writing service like this will be more readable.
create: function(datateman) {
var config = {
method: "POST",
url: baseUrl + 'insert?method=insertuser',
data: datateman,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
};
return $http(config);
}
Just add data attribute to your service.
For your code add like the following
create: function (datateman){
return $http.post(baseUrl+'insert?method=insertuser',datateman,{
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
This is the documentation
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
In your code you can do
var data = { "Value": datateman.userID + "|" + $scope.title + "|" + $scope.posttag + "|" + $scope.content } + 'your next values'.
$http.post(baseUrl+'insert?method=insertuser', JSON.stringify(data) ,{
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
Im building a RESTFul app and using Angular for my view. I want to use resources since is the best approach to it, i follow the how-to's and made some tweaks by my own to include the header api token, the code end like this:
fcbMixApp.factory('Resources', ['$resource',
function ($resource) {
return {
seminary: function (apiToken) {
return $resource('api/seminaries/:seminary', {}, {
save: {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + apiToken
}
},
update: {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + apiToken
}
}
});
},
attendant: function (apiToken) {
return $resource('api/attendants/:attendant', {}, {
save: {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + apiToken
}
},
update: {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + apiToken
}
}
});
}
}
}]);
But when i call it on my controller like this:
var Seminary = Resources.seminary(User.getAuthData().access_token);
I dont expect that line to make any request to my api, but it does. My code follows:
Seminary.query(function (data) {
$scope.seminaries = data;
});
So i finally make two calls.
What im doing wrong, or what should i change.
Thanks in advance.
You should set a header with the token:
$http.defaults.headers.common["Authorization"] = 'Bearer' + apiToken;
And not in the resource itself. You should set this when the user is logged in the first time, then you will send it on all requests.
Also consider your resource looking something like this, and making a separate one for attendant:
fcbMixApp.factory('Resources', ['$resource', function ($resource) {
function setRequestData(data) {
var requestData = new Object();
requestData.seminary = data;
return angular.toJson(requestData);
}
return $resource('api/seminaries/:seminary', {}, {
save: {
method: 'POST',
headers: {"Content-Type": "application/json"},
transformRequest: setRequestData
},
update: {
method: 'PUT',
headers: {"Content-Type": "application/json"},
transformRequest: setRequestData
}
});
}]);
Here is the solution for adding your Resource Authorization headers.
AngularJS: How to send auth token with $resource requests?
My service:
This was mistake 1 of 2 cause of my error:
getAll: function(url) {
deferred.resolve($http({ <--- deferred.resolve should not have been here
method: 'GET',
url: url,
contentType: "application/json; charset=utf-8",
cache: true,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}));
return deferred.promise;
},
Should have been instead:
getAll: function (url) {
$http({
method: 'GET',
url: url,
contentType: "application/json; charset=utf-8",
cache: true,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
My controller:
This was mistake 2 of 2 cause of my error:
// $scope.PassengerVehicles = crudSvc.getAll('/_json/PassengerVehicles.js');
// should have been:
crudSvc.getAll('/_json/PassengerVehicles.js').then(function (data) {
$scope.PassengerVehicles = data;
});
My template:
<ul data-ng-repeat="passVeh in PassengerVehicles">
<li>{{passVeh.itemId}}</li>
</ul>
Here is my plunker, which has been corrected:
AngularJS not binding promise to template
Than You Fourth!!
You have the getAll() function immediatly resolving and returning a promise to the controller. You need to allow the getAll() function to execute and deal with the promise when that resolves:
getAll: function(url) {
return $http({
method: 'GET',
url: url,
contentType: "application/json; charset=utf-8",
cache: true,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
},
and in the controller:
crudSvc.getAll('/_json/PassengerVehicles.js').success(function (vehicles){
$scope.PassengerVehicles = vehicles;
});
The difference is that you are returning a promise that immediately resolves and returns another promise. You only need to resolve the http promise.