Restangular data sent is being splitted - angularjs

Restangular.one('suppliers', 'me').getList('websites').then(
(data) ->
$scope.websites = data
$scope.websites.patch()
)
I'm just trying this for a quick test.
So the api call on /suppliers/me/websites returns an array but when I try to patch from the Restangular object it sends the data splitted as you can see below.
[{"0":"h","1":"t","2":"t","3":"p","4":":","5":"/","6":"/","7":"w","8":"w","9":"w","10":".","11":"p","12":"f","13":"c","14":"o","15":"n","16":"c","17":"e","18":"p","19":"t","20":".","21":"c","22":"o","23":"m"}]
I'm new to Angular & Restangular , what am I missing ?
Edit : To be clear, I insta patch for the test but normally I modify the websites array by adding / removing.

It looks as if you're returning a string from your service, whereas a valid JSON response is expected by Restangular.
For example:
[{"website": "http://www.example.com"}, {"website": "http://www.domain.com"}]
EDIT: I just noticed that in your question, you say your service returns an array. Double-check what it does return and make sure that it is valid JSON.
EDIT 2: It seems that Restangular expects not only valid JSON, but also JSON formatted as my code sample above is (ie. [{"key": "value"}] and not ["value"].

Related

Adding simple array to JSON payload in Bot Framework Composer

I have a simple problem where I am not able to insert an array in json payload to call graph api to update user profile while using Bot Framework Composer.
Example:
Step1. I created a property Conversation.UpdatedSkills which holds following value
["SharePoint","Dotnet","Analytics"]
Now I want to build JSON object for MS Graph service and working sample payload looks like this.
{
"skills":["SharePoint","Dotnet","Analytics"]
}
Step2. Now to build this JSON dynamically, I need pass body as JSON Object in Send an HTTP Request activity and I have folllowing code to generate payload.
{
"skills":"${conversation.UpdatedSkills}"
}
The output from Step2 looks something like this.
{
“skills”: “[\r\n “SharePoint”,\r\n “Dotnet”,\r\n “Analytics”\r\n]”
}
DESIRED JSON WAS THIS:
{
"skills":["SharePoint","Dotnet","Analytics"]
}
My question is, How do I pass my array from step 1 such a way so that it creates json object that works in service. The object created using step 2 is not the right object that service takes.
Any idea?
I tried different string manipulations but I think this is basic and there has to be something.
Don't use the string interpolation ${ }, but use an expression (=). For your example above, it should be:
{
"skills": "=conversation.UpdatedSkills"
}

How to create a Perl API to pass data back to an angularjs $http request?

I'm using angular 1.5.7 and perl 5.16.2. I don't have the ability to use any external libraries or switch tools - I'm stuck just using what's included with these two.
The angular controller is making calls to a perl file. I'm able to make POST requests successfully, and my GET requests are returning status 200 but aren't showing the data that I am expecting to see. Right now I'm just working with a simple example to try and narrow down where things are going wrong, and I think I just don't know the format to return values from the perl file.
My controller GET method looks like so:
$http({
method : "GET",
url : "filename.pl",
params:{}
}).then(function successCallback(response) {
console.log(response.records);
}, function errorCallback(response) {
console.log(response);
});
and the perl code being called in filename.pl is:
my $string = q{{"records":{"2":{"City":"México D.F.","Country":"Mexico","Name":"Ana Trujillo Emparedados y helados"},"1":{"Name":"Alfreds Futterkiste","Country":"Germany","City":"Berlin"}}}};
return $string;
The string is just a dummy variable to see if passing things back works - it won't be the final data. I have verified it is valid JSON as well. Here's what the response from the server looks like:
{"data":"","status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"glwizardutils.esp","params":{"FUNCTION":"initcheckboxes","CONTEXTID":"432"},"headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}
The data field is totally blank, and the response field doesn't work at all. I can verify it's hitting the perl file - like I said, POST requests work fine and I included some printouts that verify it's in the correct method, but it's just not returning anything. What should I be doing here instead to get this to work?
If filename.pl is invoked with HTTP, then it should be writing an HTTP response to standard output. At a minimum:
print "HTTP/1.1 200 OK\n";
print "Content-type: application/json\n";
print "\n";
my $string = q{{"records":{"2":{"City":"México ..."}}}};
print $string;
Several frameworks and modules exist in Perl and virtually every other language to handle the repetitive aspects of writing a proper response, which you will want to look into as your Perl server-side script gets more demanding.

How to pass a list value to a webapp2 backend via $.post?

In my coffeescript frontend I attempt to pass a list of value to the backend
data = {
id: [2, 3, 4]
}
$.post url, data
In the handler in a Google app engine (python) backend, I read the value like so:
id_value = self.request.get('id')
LOG.info("%s", id_value)
It always print out '2' only.
How can I get the backend to obtain the list [2,3,4]?
$.post by default sends data in url-encoded format, which handles nested structures in its own way.
You might need to encode the data in JSON before sending and then decode it on the server side - an example is here.
The request object provides a get() method that returns values for arguments parsed from the query and from POST data.
If the argument appears more than once in a request, by default get()
returns the first occurrence. To get all occurrences of an argument
that might appear more than once as a list (possibly empty), give
get() the argument allow_multiple=True.
Hence you should use something like the below snippet. You can find more details here.
id_value = self.request.get('id', allow_multiple=True)
If you need to access variables url encoded in the body of a request (generally a POST form submitted using the application/x-www-form-urlencoded media type), you should use something like this.
id_value = self.request.POST.getall('id')

Cloud Endpoints not accepting JSON array

I want to build my endpoint, which accept JSON array of below format:
[
{
"test":"Math",
"result":"Pass"
},
{
"test":"Science",
"result":"FirstClass"
}
]
It will be a POST call with the above JSON to my endpoint.
I tried it with servlet too but did not get the required result, and also tried to with list and inserting in a new class and posting to that class. Thanks in advance.
Is that an accurate representation of the JSON object which is being sent over? Because one does not simply send a a POST request with a JSON object of their param object to a cloud endpoint. See here for a thorough guide to Endpoint API interaction from a javascript perspective - notice how the client library exposes an object "gapi" through which calls are made. If you're sending this JSON from an iOS or Android app, there are similar client libraries which can be generated for you by a cloud endpoints build tool.
After much frustration, I resorted to reading the docs more carefully. In that quest, I found an important note in the doc:
https://cloud.google.com/endpoints/docs/frameworks/java/parameter-and-return-types
"Any type except a parameter or injected type is considered an entity type. ... Entity types cannot be annotated with #Named"
With all examples showing named parameters, I was stumped as the docs don't explain further, but then found a solution. It ends up that if you do not have named parameters, everything is just passed in as a LinkedHashMap. Usually, you can do any work you need to with just that data structure, but if you HAVE to have it in JSON, you can convert it. Here are some examples:
#ApiMethod(name = "endpointIterfaceName.createItems", httpMethod = "post", path = "test/items")
public WhateverReturnType createItems(LinkedHashMap<String, Object> itemsMap) {
// Do Stuff with map values
return whateverReturnValue;
}
With this, you need to be sure that you post your data with the Content-Type of json (i.e. Content-Type:application/json; charset=UTF-8). So, for example, when testing, with a jquery ajax call you would need to set dataType to "json" or with Postman, you would select "Raw" then JSON (application/json).
If you really want to convert this to a JSON object in Java because for whatever reason you can not use a hash map, you can do the following in your method:
// Use gson library to convert the map to a string
Gson gson = new Gson();
String mapAsJsonString = gson.toJson(itemsMap);
// create a JSON object from the new string representation
JSONObject obj = new JSONObject(mapAsJsonString);
As a side note, if this is passed as Content-Type:text then the whole body will be in the map as the first key of the map. You could do some inadvisable things here and just get that key and avoid converting the map to a string and then to a json object, but, like I said, that is inadvisable. :)

Grails command object fails to wire properly for delete using Restangular

I am trying to create a RESTish service using grails. I have the following...
def delete(Question q){
def text = request.reader.text;
def slurper = new JsonSlurper();
def result = slurper.parseText(text)
println "Request body is ${text} but the parsed version has a text of ${q.text} whereas the slurper gives me ${result as JSON}"
render noteService.delete(result.key)
}
This gives me an output of...
Request body is {"text":"Test Text","desc":"Test Desc","voteCount":0,"key":0} but the parsed version has a text of null whereas the slurper gives me {"desc":"Test Desc","key":0,"text":"Test Text","voteCount":0}
Why is this not wiring properly? The command object looks as follows...
#Validateable
class Question {
Integer key
String text
String desc
Integer voteCount
}
Is the delete request a GET under the hood or something? Is it expecting some other format?
Update
The create (POST) request is wiring fine which leads me to believe it is something with the differance between the Restangular call and what grails is expecting (So I think my request type guess might be right). My restangular code is simply...
this.delete = function(index) {
var questionToUpdate = _this.questions[index];
questionToUpdate.remove();
}
Also appears to fail with update (put) as well
Grails version is 2.4.3
Problem was that request.reader.text turns of the parsing of command objects.

Resources