JSON object from Angular http not deserializing properly - javascript

First here are my operating versions: node v12.13.1 | npm 6.12.1
I am having some issues understanding why this isn't de-serializing properly. I am receiving the following back from my rest service.
{ "numbers":[],
"batches":[
{ "id":"AB3E809","status":"1"},
{ "id":"EEF32A9","status":"0"}] }
These are the TypeScript interfaces I am using when trying to type the data.
interface NumJson {
status: string,
num: string
}
interface BatchJson {
id: string,
status: string
}
interface Status {
numbers: NumJson[],
batches: BatchJson[];
}
When making these calls from my Angular service, it doesn't seem to recognize or access the data properly.
this.http.get<any>(url).subscribe({
next: (data: Status) => {
console.log(data); // same as JSON above
console.log(data.numbers); // undefined
console.log(data.batches); // undefined
}
this.http.get<any>(url).subscribe({
next: (data: any) => {
console.log(data); // same as JSON above
console.log(data.numbers); // undefined
console.log(data.batches); // undefined
}
Any insights on this would be great as this is the only subscribe that is having issues.

I figured out the issue after some thought provoking examples from 'Kurt Hamilton'. My issue was with how the rest service was returning my data.
The correctly formatted data should look like this in the console:
My outputs were displaying strings; which made me question why my data was a string verse an object in the console. (A good note to take away from this issue)
After inspecting the rest service, I realized that it was doing a double serialization. Once I corrected that, the data output looked and acted correctly.

Related

Using MongoDB Stitch webhook service function, how can I convert the returned "insertedId" to string?

I'm creating MongoDB Stitch http services (using the 3rd Party Services > Incoming Webhooks > Function Editor) for a simple CRUD application and I am trying to insertOne() document and then return the document id as a string.
The insertion works as expected and I await the result and store it in a variable.
const result = await collection.insertOne(payload.query)
const id = result.insertedId
The problem is trying to convert this id to string. I'm guessing it's due to my lack of understanding the MongoDB Extended JSON and BSON types, etc. I've read all parts of the documentation that I thought could provide a solution here.
I've tried the following to convert the return value to a string:
id.toString() // logs as a string, but is an object { $oid: '507c7f79bcf86cd7994f6c0e' }
id.valueOf() // logs as a string, but is an object { $oid: '507c7f79bcf86cd7994f6c0e' }
id['$oid'] // undefined
Object.values(id.insertedId) // throws error: {"message":"'values' is not a function"}
id.str // undefined
result.str // undefined
Not sure what else to try and would really appreciate if someone can point me in the right direction here to provide a solution.
Thank you in advance.
Found a solution after noticing this section of the documentation:
MONGODB STITCH > Functions > Reference > JSON & BSON
const result = await collection.insertOne(payload.query)
const id = JSON.stringify(
JSON.parse(
EJSON.stringify(result.insertedId)
).$oid
).replace(/\W/g,'');
Seems a bit hacky just for getting the id of the document into a string, but it will work for now.

Not able to access Object values returned from a web service in React

Here are whats returned in response when hitting the service:
{
"2019-04-20":{
"fare":0,
"IsPricePos":false
},
"2019-04-19":{
"fare":0,
"IsPricePos":false
},
"2019-03-27":{
"fare":45,
"IsPricePos":true
},
"2019-03-26":{
"fare":9,
"IsPricePos":true
},
"2019-03-25":{
"fare":23,
"IsPricePos":true
}
}
Using the below code for hitting web service and getting a response:
fetch("/somepath/somefurtherpath/" + src + "/" + dst)
.then(response => response.json())
.then(result => Object.assign(newObj, result));
I am using fetch API as shown.
1) JSON.stringify(newObj) returns {} i.e. empty object string.
2) Not able to do JSON.parse(newObj) as it says its already an object.
3) Object.keys(newObj) returns an empty list.
The console.log(newObj) gives below (opening the object printed in console):
{}
2019-03-21:
IsPricePos: true
fare: 45
__proto__: Object
2019-03-22: {fare: 45, IsPricePos: true}
2019-03-23: {fare: 45, IsPricePos: true}
2019-03-24: {fare: 23, IsPricePos: true}
I need to access data in JSON and do operations on it. e.g. keys and its values.
I need to access values of fare or IsPricePos for any given dates as keys.
I tried accessing the values as newObj."2019-03-25".fare, but did not work too.
What is the best way to do this? Does React have any specific issue with this type of situation?
I tried hardcoding an object and accessing values using JavaScript, it works well. But this situation is an issue.
Please help. Thank you.

API request shows correct response in Chrome DevTools but is actually null in Angular app

My app is supposed to display Code Analysis logs. Those logs are in large(20k+ lines) html files. I'm reading them in ASP.NET Core app and pass them as string to API. C# read them nicely and passes them on, Chrome shows the correct response in DevTools, and yet Angular doesn't seem to notice this and logs null to the console aswell as when I try to display them.
I'm relatively new to Angular so I might be ommiting something obvious here. Here's my code - that's the Get method that reads and passes the file:
[HttpGet, Route("analysis")]
public string Analysis(string projectName, string definitionName)
{
string path = Path.Combine(#"\\glbuild2\CodeAnalysisLogs", projectName, definitionName, "CodeAnalysis.html");
if (System.IO.File.Exists(path))
{
string temp = System.IO.File.ReadAllText(path);
return temp;
}
else return "Error";
}
And here's the method I use to make an API request(please note it does work, I use the same method with different uri but to the same server and it works there):
this.http.get('http://localhost:54639/api/logs/analysis?projectName=' + this.currentDefinition.project.name + '&definitionName=' + this.currentDefinition.name).subscribe(data => {
this.AnalysisLogs = data;
console.log(data);
})
Now the line logging to console always logs null, and the response in DevTools is the one I'm expecting: a string going

Error: Network error: Error writing result to store for query (Apollo Client)

I am using Apollo Client to make an application to query my server using Graphql. I have a python server on which I execute my graphql queries which fetches data from the database and then returns it back to the client.
I have created a custom NetworkInterface for the client that helps me to make make customized server request (by default ApolloClient makes a POST call to the URL we specify). The network interface only has to have a query() method wherein we return the promise for the result of form Promise<ExecutionResult>.
I am able to make the server call and fetch the requested data but still getting the following error.
Error: Network error: Error writing result to store for query
{
query something{
row{
data
}
}
}
Cannot read property 'row' of undefined
at new ApolloError (ApolloError.js:32)
at ObservableQuery.currentResult (ObservableQuery.js:76)
at GraphQL.dataForChild (react-apollo.browser.umd.js:410)
at GraphQL.render (react-apollo.browser.umd.js:448)
at ReactCompositeComponent.js:796
at measureLifeCyclePerf (ReactCompositeComponent.js:75)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
at ReactCompositeComponentWrapper._updateRenderedComponent (ReactCompositeComponent.js:746)
at ReactCompositeComponentWrapper._performComponentUpdate (ReactCompositeComponent.js:724)
at ReactCompositeComponentWrapper.updateComponent (ReactCompositeComponent.js:645)
at ReactCompositeComponentWrapper.performUpdateIfNecessary (ReactCompositeComponent.js:561)
at Object.performUpdateIfNecessary (ReactReconciler.js:157)
at runBatchedUpdates (ReactUpdates.js:150)
at ReactReconcileTransaction.perform (Transaction.js:140)
at ReactUpdatesFlushTransaction.perform (Transaction.js:140)
at ReactUpdatesFlushTransaction.perform (ReactUpdates.js:89)
at Object.flushBatchedUpdates (ReactUpdates.js:172)
at ReactDefaultBatchingStrategyTransaction.closeAll (Transaction.js:206)
at ReactDefaultBatchingStrategyTransaction.perform (Transaction.js:153)
at Object.batchedUpdates (ReactDefaultBatchingStrategy.js:62)
at Object.enqueueUpdate (ReactUpdates.js:200)
I want to know the possible cause of the error and solution if possible.
I had a similar error.
I worked it out by adding id to query.
for example, my current query was
query {
service:me {
productServices {
id
title
}
}
}
my new query was
query {
service:me {
id // <-------
productServices {
id
title
}
}
}
we need to include id,
otherwise it will cause the mentioned error.
{
query something {
id
row {
id
data
}
}
}
I've finally found out what is causing this issue after battling with it in various parts of our app for months. What helped to shed some light on it was switching from apollo-cache-inmemory to apollo-cache-hermes.
I experimented with Hermes hoping to mitigate this ussue, but unfortunately it fails to update the cache the same as apollo-cache-inmemory. What is curious though is that hermes shows a very nice user friendly message, unlike apollo-cache-inmemory. This lead me to a revelation that cache really hits this problem when it's trying to store an object type that is already in the cache with an ID, but the new object type is lacking it. So apollo-cache-inmemory should work fine if you are meticulously consistent when querying your fields. If you omit id field everywhere for a certain object type it will happily work. If you use id field everywhere it will work correctly. Once you mix queries with and without id that's when cache blows up with this horrible error message.
This is not a bug-it's working as intended, it's even documented here: https://www.apollographql.com/docs/react/caching/cache-configuration/#default-identifiers
2020 update: Apollo has since removed this "feature" from the cache, so this error should not be thrown anymore in apollo-client 3 and newer.
I had a similar looking issue.
Perhaps your app was attempting to write (the network response data) to the store with the wrong store address?
Solution for my problem
I was updating the store after adding a player to a team:
// Apollo option object for `mutation AddPlayer`
update: (store, response) => {
const addr = { query: gql(QUERY_TEAM), variables: { _id } };
const data = store.readQuery(addr);
stored.teams.players.push(response.data.player));
store.writeQuery({...addr, data});
}
I started to get a similar error above (I'm on Apollo 2.0.2)
After digging into the store, I realised my QUERY_TEAM request made with one variable meta defaulting to null. The store "address" seems to use the *stringified addr to identify the record. So I changed my above code to mimic include the null:
// Apollo option object for `mutation AddPlayer`
update: (store, response) => {
const addr = { query: gql(QUERY_TEAM), variables: { _id, meta: null } };
const data = store.readQuery(addr);
data.teams.players.push(response.data.player));
store.writeQuery({...addr, data});
}
And this fixed my issue.
* Defaulting to undefined instead of null will probably avoid this nasty bug (unverified)
Further info
My issue may be only tangentially related, so if that doesn't help I have two peices of advice:
First, add these 3 lines to node_modules/apollo-cache-inmemory/lib/writeToStore.js to alert you when the "record" is empty.
And then investigate _a to understand what is going wrong.
exports.writeResultToStore = writeResultToStore;
function writeSelectionSetToStore(_a) {
var result = _a.result, dataId = _a.dataId, selectionSet = _a.selectionSet, context = _a.context;
var variables = context.variables, store = context.store, fragmentMap = context.fragmentMap;
+if (typeof result === 'undefined') {
+ debugger;
+}
Second, ensure all queries, mutations and manual store updates are saving with the variables you expect
For me adding "__typename" into query helped.
Solution for this is 1. it happening when missing id, second one is it is happening when you have same query and hitting them alternately.
Example if you have query like dog and cat.
query dog(){id, name}
query cat(){id, name }
here both query are same just their header are different, during that time, this type of issue is coming. currently i have fetching same query with different status and getting this error and am lost in search of solution.

Parse error code 121

I am trying to save a value on a 'collection' called 'orders'. But when i click 'save', it gives me an error code 121.
I have already checked my key-value parameters, but i can't find a $ or a . to make it give me this error...
Here is my code (the variable names are in portuguese, but only that)
var objRevenda = Parse.Object.extend("resellers"),
objPedido = Parse.Object.extend("orders"),
query = new Parse.Query(objRevenda),
idRevenda = $scope.revenda.id;
query.get(idRevenda, {
success: function(revenda) {
var valores = {
status: 'aberto',
client: $rootScope.usuarioAtual,
reseller: revenda,
payment_method: metodo_pgto,
items: $scope.itens,
total: $scope.totalPedido
};
var pedido = new objPedido();
pedido.save(valores, {
success: function(pedido) {
console.log('Sucesso');
},
error: function(pedido, error) {
console.error('Ops... ', error);
}
});
},
error: function(revenda, error) {
console.log(error);
}
});
Can someone help me find the error?
Btw: I am using AngularJS and Ionic Framework.
Thanks in advance.
If you are using a JSON object (sending it to Parse via AngularJS), it will have a $$hashKey, wich Angular uses to make ng-repeats and all, having unique identifiers. If you use JSON.Parse(object), Angular creates the $$hashKey, altough, if you use angular.toJson(object), the hash key should be gone. Make sure that before sending to Parse, you do a console.log(json-object), to make sure the hash key is really gone. If not, i think you should remove it by doing a conditional operation. I removed the hash key and now it works like a charm ;)
I figured out that if you are using angular (maybe other frameworks as well) that an identical embedded key/value pair on multiple levels will result in a $$hashKey key being created and will cause this error.
Maker sure that none of your objects contain something like the following:
{
id: 65ftvjbh,
user: {
id: 65ftvjbh,
name: John Doe
}

Categories