If I have a url like this "http : // x.x.x.x:port"
app.factory("myservice", function($resource){
var res = function(){
return $resource("http://x.x.x.x:port/profile/:userID", {
{
getUserInfo: {
method: "GET",
params: {userID : "userNumber"},
headers:{
"Accept": "application/json",
"Content-Type": "application/json",
sessionID : "sesionIDNumber"
}
}
},
});
}
console.log( res.get("firstName") );//error GET http://myurl/myport/profile?0=l&1=a&2=s&3=t&4=n&5=a&6=m&7=e®=%7B%2…2Fjson%22,%22sessionId%22:%22b1bfa646-215e-4223-be8c-b53d578ba379%22%7D%7D 404 (Not Found)
});
If I want to get the user's infoes, what do I have to do?
You can use like this
app.factory("myservice", function($resource)
{
return $resource('http://x.x.x.x:port/profile/:userID/:sessionID', {
userID : '#userID'
sessionID: "#sessionID"
});
});
A best example is shown below
app.factory('Books', ['$resource', function($resource) {
return $resource( '/book/:bookId',
{ bookId: '#bookId' }, {
loan: {
method: 'PUT',
params: { bookId: '#bookId' },
isArray: false
}
/* , method2: { ... } */
} );
}]);
At this point it is really simple to send requests to the web service, that we build in the previous post.Everywhere it is possible to inject the Books service it is possible to write:
postData = {
"id": 42,
"title": "The Hitchhiker's Guide to the Galaxy",
"authors": ["Douglas Adams"]
}
Books.save({}, postData);
// It sends a POST request to /book.
// postData are the additional post data
Books.get({bookId: 42});
// Get data about the book with id = 42
Books.query();
// It is still a GET request, but it points to /book,
// so it is used to get the data about all the books
Books.loan({bookId: 42});
// It is a custom action.
// Update the data of the book with id = 42
Books.delete({bookId: 42});
// Delete data about the book with id = 42
Related
I am trying to pass a variable through AJAX to an API. Here is the angular controller:
$scope.register = function() {
_.each($scope.photos, function(images) {
$upload.upload({
url: '/api/indorelawan/timaksibaik/register/upload-images',
method: 'POST',
data: {},
file: images
})
.success(function(data) {
$scope.team.photos.push(data.result.path);
})
});
$http({
method : 'POST',
url : '/api/indorelawan/timaksibaik/register',
data : $.param($scope.team),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
if (!data.success) {
...
}
else {
...
}
});
}
I tried console.log the $scope.team.photos before it calls the /register API. It displays the data perfectly. But when /register API is runned, the $scope.team.photos is not included. Here is the API:
/*Register Tim Aksi Baik*/
apiRouter.post('/timaksibaik/register', function(req, res) {
// TODO: Create new value to access general statistics data, e.g.: response time.
console.log(req.body);
var team = new GoodActionTeam();
_.each(req.body, function(v, k) {
team[k] = v;
});
team.created = new Date();
team.save(function(err, data) {
if (err) {
res.status(500).json({
success: false,
message: "Gagal menyimpan data organisasi baru.",
system_error: "Error while saving organization data: " + err.message
});
}
else {
res.status(200).json({
success: true,
message: "Organisasi Berhasil Dibuat",
result: data
});
}
});
});
The output of the req.body is only:
{ logo: '/uploads/user_avatar/register/2018-1-14_18:18:3.png',
name: 'ererr',
url_string: 'ererr',
description: 'dfdfd',
focuses: [ '549789127e6a6e2c691a1fc0', '549789127e6a6e2c691a1fc0' ] }
It looks like the $scope.team.photos is not included when the data is passed to the API. What went wrong?
The $upload.upload() is async and by the time you make a post with $scope.team there is no guarantee that all the upload success callbacks have been completed
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 make a post request through Angular. My code looks as follows,
Javascript Code looks like:
GET:
$scope.getRecord = function() {
debugger;
$http({
method: 'GET',
url: 'SomeURL'
}).then(function(response) {
debugger;
$scope.mainEntity = response.data.anEntity;
}, function(error) {
$scope.content = "something went wrong"
});
};
Post:
$scope.save = function() {
debugger;
var body = JSON.stringify({
"xyzaa": $scope.value.xyzaa || "One fielfd of its",
"xyzbb": $scope.value.xyzbb || One fielfd of its,
"xyzcc": $scope.value.xyzcc || "One fielfd of its",
"xyzaaa": $scope.value.xyzaaa || "One fielfd of its"
});
var request = {
method: 'POST',
url: 'Some URL',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
data: body
};
$http(request).then(function (result) {
debugger;
$scope.getRecord();
}, function (error) {
debugger;
console.log(error)
alert("error")
})
};
Well, I can see that the post request returns the data that I have done in a JSON Format, yet am receiving the error:
POST http://localhost:xyz/xyz/a (Unprocessable Entity)
Object {data: Object, status: 422, config: Object, statusText: "Unprocessable Entity"}.
I can see that data that am being posting is getting in the data key and I can see the data that I have passed, yet I get this error and it doesnt change in the api
I'm trying to send the post request to server with post data
it's sent the request to the server, but not in right format
request url like /rest/api/modifyuser/?currentPassword=admin&newPassword=admin
it's like GET request - (may be this is problem)
I'm new to angularjs . please share idea to solve this problem
Here is my code
In controller
var currentPass = "admin";
var newPass = "admin";
var confirmPass = "admin";
var authToken = "abcdef";
User.changePassword(currentPass, newPass, confirmPass, authToken, function(response) {
angular.forEach(response, function (item) {
alert("resp"+ item);
});
});
In services
UIAppResource.factory('User', function($resource) {
return {
changePassword: function(currentPass, newPass, confirmPass, authtoken, callback) {
var Resq = $resource(baseURL + "modifyuser", {}, {
'query': {
method: 'POST',
params: {
'currentPassword': currentPass,
'newPassword': newPass,
'confirmPassword': confirmPass
},
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'X-Internal-Auth-Token': authtoken
},
isArray: false
}
});
Resq.query(callback);
}
};
});
Thanks in advance
I dont want to say you are doing it all wrong.. but you are def. abusing things. The default way to POST something with ng-resource is to use save. Second, the default way to send data is to instantiate a $resource factory with the data you want. See _resource below. We pass the data we want, and it will automagically convert it and if its a POST send it in the body, or in the case of a GET it will turn into query parameters.
UIAppResource.factory('User', function($resource) {
return {
changePassword: function(currentPass,
newPass,
confirmPass,
authtoken,
callback
) {
var Resq = $resource(baseURL + "modifyuser", {}, {
'save': {
method: 'POST',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'X-Internal-Auth-Token': authtoken
}
}
});
var _resource = new Resq({
'currentPassword': currentPass,
'newPassword': newPass,
'confirmPassword': confirmPass
});
_resource.$save(callback);
}
};
});
I want the user to be able to set the slug name (URL) for a document in my app, but also I need some control so users don't override each other. It needs to be a separate call (not integrated with create/update) so the user can get visual feedback on their own slug name suggestions.
Therefore I've created a suggestSlug API call that takes an optional slug parameter as seed for the final slug name.
This is what my Express routes looks like:
app.get('/api/projects/suggestSlug/:slug', projects.suggestSlug);
app.get('/api/projects/suggestSlug', projects.suggestSlug);
app.get('/api/projects', projects.list);
app.get('/api/projects/:id', projects.show);
Now, I want to extend ngResource on the client side (AngularJS) to make use of this API:
angular.module('myapp.common').factory("projectModel", function ($resource) {
return $resource(
"/api/projects/:id",
{ id: "#id" },
{
update: { method: "PUT", params: { id: '#_id' } },
del: { method: "DELETE", params: { id: '#_id' } }
}
);
});
How do I extend the ngResource client to use my new API?
This was my solution: adding a separate $http-based method to my projectModel:
angular.module('myapp.common').factory("projectModel", function ($resource, $http) {
var projectModel = $resource(
"/api/projects/:id",
{ id: "#id" },
{
update: { method: "PUT", params: { id: '#_id' } },
del: { method: "DELETE", params: { id: '#_id' } }
}
);
projectModel.suggestSlug = function (slugSuggestion, callback) {
$http.get(
'/api/projects/suggestSlug/' + slugSuggestion
).success(callback).error(function(error) {
console.log('suggestSlug error:', error);
});
};
return projectModel;
});