I have a service that I am calling to get a collection which works fine. Here is the service:
angular.module('clinicalApp').factory('encounterService', function ($resource, $rootScope) {
var EncounterService = $resource('http://localhost:port/v2/encounters/:encounterId', {encounterId:'#id', port: ':8280'}, {
search: {
method: 'GET',
headers: {
'User': 'testuser',
'Content-Type': 'application/json'
}
},
save: {
headers: {
'User': 'testuser',
'Content-Type': 'application/json'
}
}
});
return EncounterService;
});
As I said, I am able to get the collection, but when I try to update a one of the elements in my collection, it is calling out to the wrong url. Here is how I am trying save my resource:
encounterService.save({
id: scope.encounter.id
});
And here is the url that is being hit:
http://localhost:8280/v2/encounters?id=12345
So it is appending the url as if it is a search parameter. How do I get it to append the id to the url like
encounters/12345
as it should?
Try this...
{encounterId:'#id', port: ':8280'}
Change To:
{encounterId:'#encounterId', port: ':8280'}
AND
encounterService.save({
id: scope.encounter.id
});
Change To:
encounterService.save({
encounterId: scope.encounter.id
});
Related
Here im trying to posting data from angular to api server in angular side it maping properly but wht it not binding at serverside
Emplyeectr.js
Emplyeeserve.js
this.saveEmp = function (savingdata) {
var sersave = $http({
url: Privateurl2+'SaveEmpData',
method: "POST",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: JSON.stringify(savingdata),
content: { 'content-type': 'application/Json' }
})
return sersave;
}
Emplyeectrl.js
$scope.SaveDb = function (user) {
if ($scope.Validate = "UpdateEmpDetails")
$scope.Submitted = true;
if ($scope.isFormValid) {
var savingdata = {
EmpName: $scope.User.EmpName,
Gen_Name: $scope.User.Gen_Name,
Email: $scope.User.Email,
Psw: $scope.User.Psw,
Cnt_Id: $scope.User.Cnt_Id,
Sts_Id: $scope.User.Sts_Id,
City_Id: $scope.User.City_Id,
}
var saving = Myservice.saveEmp(savingdata);
saving.then(function () {
})
}
}
When i trace it from Fiddler it passing data as
{"EmpName":"Aa1.com","Gen_Name":"Male","Email":"Das#gmail","Psw":"1478","Cnt_Id":2,"Sts_Id":4,"City_Id":7}
The content you are posting is not in the correct format. You are trying to post JSON but telling the server it's form data.
You should change
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
to
headers: { 'Content-Type': 'application/json' },
you should probably remove the content property as it's not in the AngularJS docs and probably a little mis-leading.
I have the following REST Service which I have to access on POST Method,
I can access it via jQuery but I don't know how to do it with AngularJS (v1)
<string xmlns = "http://schemas.microsoft.com/2003/10/Serialization/">
<script id = "tinyhippos-injected" />
{
"volumeResult": {
"gyydt": "9771241.17704773",
"gytotal": "29864436.1770477",
"gybudgeted": "29864436.1770477",
"lyydt": "10197350",
"lytotal": "27859381",
"lybudgeted": "10197350",
"cyytd": "6992208",
"lastUpdate": "March-2017"
},
"valueResult": {
"gyydt": "26862094",
"gytotal": "68217952",
"gybudgeted": "68232952",
"lyydt": "0",
"lytotal": "0",
"lybudgeted": "0",
"cyytd": "68217952",
"lastUpdate": "March-2017"
},
"trucksResult": {
"gyydt": "165951",
"gytotal": "497879",
"gybudgeted": "497879",
"lyydt": "168822",
"lytotal": "468814",
"lybudgeted": "168822",
"cyytd": "119442",
"lastUpdate": "March-2017"
}
}
</string>
Here is my controller.js:
angular.module('starter.controllers', [])
.controller('DashCtrl', ['$scope', '$http', function ($scope, $http) {
$http({
//headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
headers: {'Content-Type' : 'application/json'},
url: 'https://myurl../api/getHPData',
method: 'POST',
// data: data,
params: {
"stationId": 263,
"crusherId": 27,
"monthYear": '2016-04'
}
})
.then(function (response) {
console.log(response);
})
// I don't have to use .success and .error function as they are [depricated][2]
//.success(function (data, status, headers, config) {
// $scope.greeting = data;
// var Result = JSON.stringify(data);
// var Result = JSON.parse(data);
//})
//.error(function (error, status, headers, config) {
// console.log("====================== Error Status is: " + error);
// console.log("====================== Status is: " + status);
// console.log("====================== Error occured");
//})
}]) // eof controller DashCtrl
.controller('MapsCtrl', function($scope) {})
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
What I want is value of:
"volumeResult" > "gytotal"
Problems:
It always return:
Object {data: "{"result":"false"}", status: 200, config: Object, statusText: "OK", headers: function}
and
When I pass monthYear without quotes it process (arithmetic) it as (2016-04 = 2012)
As the service is POST but when I analyze it in Chrome Developers Tool so I get: (Query String, which isn't meant to be POST)
ionic.bundle.js:25005
XHR finished loading: POST
"https://myurl../api/getHPData?crusherId=27&monthYear=2016-4&stationId=263"
Possible solutions:
Either I am using wrong header:
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json'
},
Or header may be,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
Or as per my friend says:
When I change your code to use the code above, I get this error:
"{"Message":"The requested resource does not support http method
'OPTIONS'."}" Which means that there is a CORS (Cross-origin Resource Sharing) issue. Chrome is trying to make a "preflight" request to allow
CORS, but the server doesn't know what to do with it.
But I don't think it is because of this as I am receiving:
Object {data: "{"result":"false"}", status: 200, config: Object,
statusText: "OK", headers: function}
from server. Noted that: {"result":"false"} is the message displayed by the server when it didn't find data or you pass wrong parametes. Also bellow jQuery code is proof that I can access the server. :)
Edit
jQuery Snippet:
<script>
$(document).ready(function() {
get_homepage_data(263, 27, '2016-04');
function get_homepage_data(stationIds, crusherIds, date) {
var url = "https://myurl..";
var data_to_send = {
'stationId': stationIds,
'crusherId': crusherIds,
'monthYear': date
};
console.log("Value is: " + JSON.stringify(data_to_send));
//change sender name with account holder name
// console.log(data_to_send)
$.ajax({
url: url,
method: 'post',
dataType: 'json',
//contentType: 'application/json',
data: data_to_send,
processData: true,
// crossDomain: true,
beforeSend: function () {
}
, complete: function () {}
, success: function (result1) {
// I know I can do it in one line but lazy enough to edit it here :p
var Result = JSON.parse(result1);
var value_data = Result["valueResult"];
var foo = value_data["gyydt"];
console.log("Log of foo is: " + foo);
var foo2 = 0;
// 10 lac is one million.
foo2 = foo / 1000000 + ' million';
console.log(JSON.stringify(value_data["gyydt"]) + " in million is: " + foo2);
}
, error: function (request, error) {
return false;
}
});
}
}); // eof Document. Ready
</script>
Output of above script is script is:
Value is: {"stationId":263,"crusherId":27,"monthYear":"2016-04"}
XHR finished loading: POST "https://myurl../api/getHPData".
Log of foo is: 26862094
"26862094" in million is: 26.862094 million
Which is indeed perfect. :)
try to use $http this way ..
$http.post("https://myurl../..",JSON.stringify({
stationId: 263,
crusherId: 27,
monthYear:'2016-04'
})).then(function(res){
console.log(res);
}).catch(function(errors){
console.log(errors);
})
I got answer. Whao.
Thank you georgeawg for his answer:
He says:
When posting form data that is URL encoded, transform the request with the $httpParamSerializer service:
$http({
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
url: 'https://myurl..',
method: 'POST',
transformRequest: $httpParamSerializer,
transformResponse: function (x) {
return angular.fromJson(angular.fromJson(x));
},
data: {
"stationId": 263,
"crusherId": 27,
"monthYear": '2016-04'
}
})
.then(function(response) {
console.log(response);
$scope.res = response.data;
console.log($scope.res);
});
Normally the $http service automatically parses the results from a JSON encoded object but this API is returning a string that has been doubly serialized from an object. The transformResponse function fixes that problem.
Now I am able to get value of gytotal as:
var myData = parseFloat(response.data.valueResult.gytotal);
console.log(myData);
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)
});
everything lives in the title.
when producing a resource in angular :
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id');
}]);
and using in a controller :
MyResource.save({att: att, att2: att2});
the Service sends the data in a json artifact ahead to the server.
I need to send the data in a x-www-form-urlencoded shape.
Where ought I modify my code to resolve that ?
Should pass the headers parameters
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id', {}, {
save: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
});
}]);
then serialize your data before sending them with $httpParamSerializer
myModule.controller('appController', function ($httpParamSerializer) {
MyResource.save($httpParamSerializer({att: att, att2: att2}));
}
Complete answer (since angular 1.4). You need to include de dependency $httpParamSerializer
var res = $resource(serverUrl + 'Token', { }, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
res.save({ }, $httpParamSerializer({ param1: 'sdsd', param2: 'sdsd' }), function (response) {
}, function (error) {
});
I finally found myself:
When defining a resource and the associated instruction, the "headers" parameter comes in hand.
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id', {}, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
}]);
js
what I'm trying to do is making REST API REQUEST to server.
A request should be 'GET' method and include 'Authorization' header.
my factory code which communicate REST server is like this
'use strict';
angular.module('mabidualApp')
.factory('User', function ($resource, config) {
return $resource(config.API+':url/:id', {
url: '#url', id: '#id'
}, { //parameters default
auth: {
method: 'POST',
params: {
url: "token",
}
},
get: {
method: 'GET',
headers:{'Authorization':'Bearer oLDMYrJD0Qg15Nhv7N-H6w'} ,
params: {
url:"users",
id:'me'
}
}
});
the fitst problem is here
headers:{'Authorization':'Bearer oLDMYrJD0Qg15Nhv7N-H6w'} ,
If I add header the method changes to 'OPTIONS' not 'GET'. I found out it's about CORS preflight something, but I couldn't figure it out how to disable it..
so I tried to change my configuration in app.js
.config(function($locationProvider, $routeProvider, $httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$httpProvider.defaults.headers.get['Authorization'] ='Bearer oLDMYrJD0Qg15Nhv7N-H6w';
the second problem is here
$httpProvider.defaults.headers.get['Authorization'] ='Bearer oLDMYrJD0Qg15Nhv7N-H6w';
It makes the error below.
Cannot set property 'Authorization' of undefined
Is there any solution to send A 'GET' request with 'Authorization' header?
thanks
I think you're using params in the wrong way in your get request. Try switching params and headers like that :
angular.module('mabidualApp')
.factory('User', function ($resource, config) {
return $resource(config.API+':url/:id', {
url: '#url', id: '#id'
}, { //parameters default
auth: {
method: 'POST',
params: {
url: "token",
}
},
get_auth: {
method: 'GET',
params: {
url:"users",
id:'me'
},
headers: {'Authorization':'Bearer oLDMYrJD0Qg15Nhv7N-H6w'}
}
});
I changed your custom get request because 'get' might be defined by angular already, but I'm not sure :
$httpProvider.defaults.headers.get_auth['Authorization'] ='Bearer oLDMYrJD0Qg15Nhv7N-H6w';
Besides, are you sure you don't need any other headers?