Angular $http.get losing decimals when parsing response to json object - json

I'm using $http.get to make a request to an API which return this message:
{code":0,"message":"OK","return":{"exchangeRate":**1.0000000**,"oAmmount":**100.00**,"dAmmount":**100.00**,"tokenRequired":{"email":false,"physicalToken":false,"sms":false}}}
As you see this is a well formed JSON. When the $http.get fires the success the object injected as a parameter to the function loses the decimal places for the exchangeRate, oAmmount and dAmmount.
$http.get(url, SERVICE_CONFIG.config)
.success(function(data) {
//My Stuff
})
I've tried passing in the config object the following object {timeout: 20000, responseType: "json"}
When debugging the app I see the data object as {exchangeRate: **1**, oAmmount: **100**, dAmmount: **100**, tokenRequired: ...}
Any idea why I'm loosing the decimal places on the floats?
Thnx!

Related

Angular: Observable with subscribe returns error 200 OK as the response is not JSON

I am developing a front-end web application using Angular 11. This application uses several services which return data in JSON format.
I use the async / await javascript constructs and the Observables to get the answers from these services. This is an example my call:
let myResponse = await this.myService(this.myData);
myResponse.subscribe(
res => {
console.log("Res: ",res)
}, (error) => {
console.log("Error: ",error)
}
);
where this.myService contains the code doing the HTTP call using Angular httpClient.
Unfortunately a specific service (only one!) doesn't return data in JSON format but it returns a byte array (string that identifies a pdf -format application/pdf-).
Unfortunately this invocation causes a very strange error with code 200 OK:
How can I do to prevent res from being interpreted as JSON and therefore this error being reported? How can I read resreporting that it will not be in json format?
This service has no errors (with Postman it works perfectly). The problem is Javascript and Observable which are interpreted as JSON. How can I read the content of res in this case?
If a HTTP API call is not returning a JSON, just provide the proper value in the responseType option:
this.httpClient.get('<URL>', {
responseType: 'arraybuffer'
});
Ref: https://angular.io/api/common/http/HttpClient#description

Send a queryset of models from Django to React using Ajax

I've been looking for info about this for hours without any result. I am rendering a page using React, and I would like it to display a list of Django models. I am trying to use ajax to fetch the list of models but without any success.
I am not sure I understand the concept behind JSon, because when I use the following code in my view:
data = list(my_query_set.values_list('categories', 'content'))
return JsonResponse(json.dumps(data, cls=DjangoJSONEncoder), safe=False)
It seems to only return a string that I cannot map (React says that map is not a function when I call it on the returned object). I thought map was meant to go through a JSon object and that json.dumps was suppose to create one...
Returned JSon "object" (which I believe to just be a string):
For the time being I have only one test model with no category and the content "At least one note "
[[null, "At least one note "]]
React code:
$.ajax({
type:"POST",
url: "",
data: data,
success: function (xhr, ajaxOptions, thrownError) {
var mapped = xhr.map(function(note){
return(
<p>
{note.categories}
{note.content}
</p>
)
})
_this.setState({notes: mapped})
},
error: function (xhr, ajaxOptions, thrownError) {
alert("failed");
}
});
Can someone please point me to the best way to send Models from Django to React, so I can use the data from this model in my front end?
I recommend using the Django REST Framework to connect Django to your React front-end. The usage pattern for DRF is:
Define serializers for your models. These define what fields are included in the JSONified objects you will send to the front-end. In your case you might specify the fields 'categories' and 'content.'
Create an API endpoint. This is the URL you will issue requests to from React to access objects/models.
From React, issue a GET request to retrieve a (possibly filtered) set of objects. You can also set up other endpoints to modify or create objects when receiving POST requests from your React front-end.
In the success function of your GET request, you will receive an Array of Objects with the fields you set in your serializer. In your example case, you would receive an Array of length 1 containing an object with fields 'categories' and 'content.' So xhr[0].content would have the value "At least one note ".
In your code, the call to json.dumps within the JsonResponse function is redundant. Check out the docs for an example of serializing a list using JsonResponse. If you are serializing the object manually (which I don't recommend), I'd use a dictionary rather than a list -- something like {'categories': <value>, 'content' : <value>}. DRF will serialize objects for you like this, so the fields are easier to access and interpret on the front-end.

Get real response of ngResource save()

I have the following situation:
I use ngResource to save some data to the mysql database and after the successfull save() I want to log the json response the server sends to me:
Document.save({}, postData, function(response){
console.log(response);
});
This does not result in a simple response, but in something like an object with its own methods. I want some smple output like the response.data after an $http.$get:
{
"docClass":"testets",
"colCount":1,
"columns":null,
"groupid":7,
"id":19,
"lang":"de",
"title":"test",
"version":1409849088,
"workflow":"12234"
}
Greets
Check out this answer
Promise on AngularJS resource save action
So I think in your case you need to do
var document = new Document(postData);
document.$save()
.then(function(res){});
But also from the link I provided
This may very well means that your call to $save would return empty reference. Also then is not available on Resource api before Angular 1.2 as resources are not promise based.

Parse JSON returned from NODE.js

I’m using jQuery to make an AJAX call to Node.js to get some JSON. The JSON is actually “built” in a Python child_process called by Node. I see that the JSON is being passed back to the browser, but I can’t seem to parse it—-although I can parse JSONP from YQL queries.
The web page making the call is on the same server as Node, so I don’t believe I need JSONP in this case.
Here is the code:
index.html (snippet)
function getData() {
$.ajax({
url: 'http://127.0.0.1:3000',
dataType: 'json',
success: function(data) {
$("#results").html(data);
alert(data.engineURL); // alerts: undefined
}
});
}
server.js
function run(callBack) {
var spawn = require('child_process').spawn,
child = spawn('python',['test.py']);
var resp = '';
child.stdout.on('data', function(data) {
resp = data.toString();
});
child.on('close', function() {
callBack(resp);
});
}
http.createServer(function(request, response) {
run(function(data) {
response.writeHead(200, {
'Content-Type':
'application/json',
'Access-Control-Allow-Origin' : '*' });
response.write(JSON.stringify(data));
response.end();
});
}).listen(PORT, HOST);
test.py
import json
print json.dumps({'engineName' : 'Google', 'engineURL' : 'http://www.google.com'})
After the AJAX call comes back, I execute the following:
$("#results").html(data);
and it prints the following on the web page:
{“engineURL": "http://www.google.com", "engineName": "Google"}
However, when I try and parse the JSON as follows:
alert(data.engineURL);
I get undefined. I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Could anyone advise if I’m doing something wrong building the JSON in Python, passing the JSON back from Node, or simply not parsing the JSON correctly on the web page?
Thanks.
I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Yes, the ajax response is a string. To get an object, you have to parse that JSON string into an object. There are two ways to do that:
data = $.parseJSON(data);
Or, the recommended approach, specify dataType: 'json' in your $.ajax call. This way jQuery will implicitly call $.parseJSON on the response before passing it to the callback. Also, if you're using $.get, you can replace it with $.getJSON.
Also:
child.stdout.on('data', function(data) {
resp = data.toString();
// ^ should be +=
});
The data event's callback receives chunks of data, you should concatenate it with what you've already received. You probably haven't had problems with that yet because your JSON is small and comes in a single chunk most of the time, but do not rely on it, do the proper concatenation to be sure that your data contains all the chunks and not just the last one.

JSON to usable array javascript

I'm trying to convert my JSON code to a usable array in javascript/jquery.
I have the following JSON code arriving via ajax:
[{"id":"9","firstname":"Greg","surname":"Bril","position":"0","busy":"0","disabled":"0"},{"id":"14","firstname":"Nai","surname":"Brooks","position":"1","busy":"0","disabled":"0"},{"id":"17","firstname":"Margaret","surname":"Grey","position":"1","busy":"0","disabled":"0"},{"id":"1","firstname":"Cameron","surname":"Grover","position":"0","busy":"0","disabled":"0"},{"id":"2","firstname":"Sarah","surname":"Grover","position":"0","busy":"0","disabled":"0"},{"id":"3","firstname":"Margaret","surname":"Hynes","position":"0","busy":"0","disabled":"0"},{"id":"4","firstname":"Stephen","surname":"Hynes","position":"0","busy":"0","disabled":"0"},{"id":"11","firstname":"Ben","surname":"Mills","position":"1","busy":"0","disabled":"0"},{"id":"15","firstname":"Elizabeth","surname":"Mills","position":"1","busy":"0","disabled":"0"},{"id":"10","firstname":"Grant","surname":"Mills","position":"0","busy":"0","disabled":"0"},{"id":"16","firstname":"John","surname":"Mills","position":"1","busy":"0","disabled":"0"},{"id":"13","firstname":"Lucinda","surname":"Ower","position":"1","busy":"0","disabled":"0"},{"id":"12","firstname":"Karina","surname":"Scott","position":"1","busy":"0","disabled":"0"}]
It is created and intepreted using:
$.getJSON( "tc_search1.php", {
leave: $("input#leave").val(),
end: $("input#end").val(),
override: $("#tc_override").is(":checked"),
tc_id: $("#tc_id").val()
}, function(data) {
//i cant get this part to work
});
I can't seem to manage to get the function on success to work. I tried the $.each method on jquery documentation website, but I can't get it right. Can anyone help?
The getJSON method will automatically parse the JSON string into a Javascript object.
The data parameter in your success callback function will be an array of objects. For example, the expression data[0].firstname will return "Greg".