Currently I have a resource like so:
return $resource(usersUrl, {}, {
//The data model is loaded via a GET request to the app
query: {method: 'GET', params: {}, isArray: false},
putupdate: {method: 'PUT', params:{}}
});
Now I would like to put some JSON that looks like:
{"providerid":"userpass","firstname":"t","lastname":"b","fullname":"t b","email":"emailaddress,"avatarurl":"http:/.....","passwordset":true}
Anyway as you can see it doesn't have a top level name, if I pass this information in as a parameter to the resource a name is appended to the json like:
myparam:{"providerid":"userpass","firstname":"t","lastname":"b","fullname":"t b","email":"emailaddress,"avatarurl":"http:/.....","passwordset":true}
Is there a away of preventing this from happening as the server side doesn't like it?
Thanks
Tom
From your question it sounds like you are trying to use $resource to post some arbitrary json data. If this data is not a Resource() you should simply use $http.
$http.put(theUrl, theJsonData);
If it is actually a Resource() you can just call the method you declared when building your resource.
myResource.putupdate();
Related
I am learning Angluarjs's $resource. I set a button on HTML for deleting a record from a json file,and hope to delete one record from testForm.json file. Unfortunately, I failed to do so and can't solve the problem.
The codes are here: my Angularjs code
The deleting function in controller codes is shown as follows
$scope.deleteRecord = function () {
var id = 1;
var arecord = new singleResource();
arecord.$get({userId:id},function () {
$log.info(arecord);
arecord.$delete();
});
The HTML part of the deleting function is shown here:
<div class="form-group">
<div class="col-sm-6 col-sm-push-2">
<button type="button" class="btn btn-primary" ng-click="deleteRecord()">Delete information</button>
</div>
</div>
"$scope.deleteRecord" is the function that when clicking the Delete information button, the record with id=1 in json file should be removed. The error says:"DELETE http://localhost:3000/contactInfo 404 (Not Found) :3000/contactInfo:1 ", while the "arecord" is shown as an object in the log "m {email: "333#333", password: 321, method: "Internet", id: 1, $promise: undefined…}", which should be fine.
$http
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
$http is built into Angular, so there’s no need for the extra overhead of loading in an external dependency. $http is good for quick
retrieval of server-side data that doesn’t really need any specific
structure or complex behaviors. It’s probably best injected directly
into your controllers for simplicity’s sake.
$resource
The action methods on the class object or instance object can be invoked >with the following parameters:
HTTP GET "class" actions: Resource.action([parameters], [success], [error])
non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
$resouce is good for situations that are slightly more complex than $http. It’s good when you have pretty structured data, but you
plan to do most of your crunching, relationships, and other operations
on the server side before delivering the API response. $resource
doesn’t let you do much once you get the data into your JavaScript
app, so you should deliver it to the app in its final state and make
more REST calls when you need to manipulate or look at it from a
different angle.
Alternatively you could use: restangular https://github.com/mgonto/restangular
Restangular is a perfect option for complex operations on the client side. It lets you easily attach custom behaviors and interact
with your data in much the same way as other model paradigms you’ve
used in the past.
Angularjs guide: https://docs.angularjs.org/api/ng/service/$http#delete
try with the delete method:
$scope.deleteRecord = function () {
var id = 1;
var arecord = new singleResource();
arecord.$delete({userId:id},function () {
$log.info(arecord);
//arecord.$delete();
});
or
$http({
method: 'DELETE',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I hope it helps.
I am trying to send a get request to my rails backend using angular. So what am looking for is the request like this
Parameters: {"location"=>"london", "q"=>{"price_gteq":"33333", "price_lteq":"7777"}}
So in my app.js I tried below code to send the request with the parameters. I am now getting unexpected / and the second nested parameter is not showing aswell as seen below.
$http({
url: "/search.json",
method: "GET",
params: {location: $scope.searchLocation, q: {price_gteq: $scope.min_price, price_lteq: $scope.max_price} }
})
This is what i get when I try like above
Parameters: {"location"=>"london", "q"=>"{\"price_gteq\":\"33333\"}"}
Could someone tell me what am doing wrong here??
By default angular uses $httpParamSerializer which actually can handle nested parameters. Check if your $http uses this service. If for some reason it doesn't work, you can write own paramSerializer and pass it into $http configuration object.
Also check if price_lteq present at the moment, when you send request.
I'm attempting to build a web app using Spotify's web API however, I find their tutorial lacking. The way it works is data is requested using POST and GET functionality and sent back using JSON. Seems easy enough, want to get information about an artist? Just call GET https://api.spotify.com/v1/artists/0OdUWJ0sBjDrqHygGUXeCF and you get a nice JSON document with information about the requested artist.
The problem is I don't know how to make that GET call. jQuery has get and post methods both with "data" parameters but I'm not sure on the syntax necessary, especially when it comes to exchanging an authorization code for an access token. If you visit Spotify's authorization guide and scroll to step 4 of the Authorization Code Flow you can see I need to make a POST call to https://accounts.spotify.com/api/token. The call must have 3 request body parameters and 1 header parameter and upon succession a JSON file with the appropriate data is in the response body.
My question is how do I make POST and GET calls that have body parameters and header parameters and how do I extract the JSON data from the response body after a successful call?
As you can see from their code examples & libraries and this jsFiddle, their getUserData request is nothing but a simple ajax call, which contains their url and a headers object (which contains a prefix string concatenated with the accessToken) as parameters:
function getUserData(accessToken) {
return $.ajax({
url: 'https://api.spotify.com/v1/me',
headers: {
'Authorization': 'Bearer ' + accessToken
}
});
}
Generally, when you need to pass parameters in an $.ajax call, just do as shown above, or construct an object first and include it like this:
YourObj = {
url: "your url here",
param2: "param val 2",
param3: "param val 3",
...
}
$.ajax(YourObj).done(function(data){
//do something with the returned data here, e.g.
console.log("data: ", data);
});
This approach can be useful if your parameters are dependent on other values which are not so readily avalable.
If I submit a form using POST, the ASP.NET server can access each value by name. However, if I do it with javascript like:
$http({
method: "POST",
url: TDSV.ROOT_PATH + "/themes/" + data.id,
params: { "xHttpMethodOverride": "PUT" },
data: { "newContent": JSON.stringify({ properties: data.json.properties, "otherInfo": "hello world" }, null, "\t") },
cache: false
});
It is all squashed together into a giant stream that I have to parse through. I have no interest in sending files this way. I just want to separate the strings by name. Is there a way to do this?
It looks like you are using WebForms, if that´s the case you must send the data in a different way.
Here is a tutorial, please take a look and let me know if that helps:
http://www.bennadel.com/blog/2615-posting-form-data-with-http-in-angularjs.htm
I'm looking for a way to return a single JSON/JSONP string from a cross-domain "AJAX" request. Rather than request the string and have JQuery return it as a generic object automatically, I want to get a hold of the string BEFORE that conversion happens. The goal here is to parse it myself so I can turn it straight into new objects of a certain type (e.g. a Person object).
So, just to make this clear, I don't want any string-to-generic-object conversion going on behind the scenes and this must work using a different domain.
Here's a non-working example of what I would like to do:
$.ajax({
type: 'GET',
url: 'http://www.someOtherDomain.com/GetPerson',
dataType: 'text',
success: parseToPerson
});
function parseToPerson( textToParse ) {
// I think I can do this part, I just want to get it working up to this point
}
I'm perfectly happy if JQuery isn't involved in the solution, as long as it works. I would prefer to use JQuery, though. From what I've read, the javascript techniques used to get JSONP data (dynamically creating a script element) would probably work, but I can't seem to get that to work for me. I control the domain that I am requesting data from and I can get the data if I change the dataType in the AJAX call to 'JSONP', so I know that is working.
If your data is being retrieved from another domain, you will need to use JSONP (there are other options, but JSONP is by far the easiest if you control the service). The jQuery call will look like this:
$.ajax({
// type: 'GET', --> this is the default, you don't need this line
url: 'http://www.someOtherDomain.com/GetPerson',
dataType: 'jsonp',
success: parseToPerson
});
The actual request that goes to your service will be http://www.someOtherDomain.com/GetPerson?callback=arbitrary_function_name. On the service side, you will need to return data like this:
arbitrary_function_name("the string (or JSON data) that I want to return");
So you'll need to inspect the querystring parameters, get the value of the callback parameter, and echo it out as if you're calling a Javascript function with that name (which you are), passing in the value you want to provide through the service. Your success function will then get called with the data your service provided.
If you're deserializing the returned data into a Javascript object, you might be better off returning JSON data than a string, so the data your service returns might look like this:
arbitrary_function_name({
"name":"Bob Person",
"age":27,
"etc":"More data"
});
That way you don't have to worry about parsing the string - it'll already be in a Javascript object that's easy to use to initialize your object.
Not sure how this will work in conjuction with jsonp, but maybe converters is what you're looking for?
$.ajax(url, {
dataType: "person",
converters: {
"text person": function(textValue) {
return parseToPerson(textValue);
}
}
});