angular2 transformRequest usage for xml to json conversion - json

I managed to convert xml response into json format in angular 1 using the code below. But how can I use similar code in angular2,
var xml = function () {
$http.get("./app/sampleXML.xml",
{
transformResponse: function (cnv) {
var x2js = new X2JS();
var aftCnv = x2js.xml_str2json(cnv);
return aftCnv;
}
})
.success(function (response) {
console.log(response);
});
}
Angular2:
getXml() {
this.http.get('../../jsonConfig/sampleXML.xml')
.map(response => response.text())
.subscribe(data => {
if(data) {
console.log(data);
}
});
}

This is what worked for me :
xml_str2json(extractXML(data.text(),'string1','string2'))
where xml2json comes from the following library :
https://github.com/abdmob/x2js
and extractXML is a string function that enables me to extract the xml body from the SOAP response.
I could not find any document on the methods that could be applied on a Response.
Hope this may help.
Cheers.

Related

Next JS Error serializing `.dehydratedState.queries[0].state.data.config.adapter` returned from `getServerSideProps

I am trying to use react-query to fetch data in getServerSideProps in Next JS but I keep getting this weird error:
Error: Error serializing `.dehydratedState.queries[0].state.data.config.adapter` returned from `getServerSideProps` in "/auth/google/callback".
Reason: `function` cannot be serialized as JSON. Please only return JSON serializable data types.
Here is my code:
// Packages
import { useRouter } from 'next/router'
import { dehydrate, QueryClient, useQuery } from 'react-query';
// APIs
import { completeGoogleAuth } from '../../../hooks/auth';
export async function getServerSideProps(context) {
const queryClient = new QueryClient()
await queryClient.prefetchQuery('completeGoogleAuth', () => completeGoogleAuth(context.query.code));
return {
props: {
dehydratedState: dehydrate(queryClient),
},
}
}
export default function Callback() {
const router = useRouter();
const { data } = useQuery('completeGoogleAuth', () => completeGoogleAuth(router.query.code))
return (
<>
Loading
</>
)
}
I have tried to use JSON.stringify(dehydrate(queryClient)) and also used JSON.parse(JSON.stringify(dehydrate(queryClient))) but none of them worked.
What can I do?
I stumbled across the same error just today, JSON.stringify(dehydrate(queryClient)) or serializing dehydrate(queryClient) by any means won't really work as the object your completeGoogleAuth function is returning has function values in the key-value pairs, here's a picture of the config object.
And as you know, functions can't be JSON serialized as straightforwardly. Now, what I assume you used(or what I did too) for the completeGoogleAuth fetcher function is use Axios as your API client library. I have found that Axios returns objects that can't be JSON serialized. As a solution, I have just used the native JavaScript fetch() API to get API data and the haven't faced any issues since then.
Here's my fetcher function:
export const getScholarshipInfoSSR = async (token) => {
const response = await fetch(
process.env.NEXT_PUBLIC_API_BASE_URL + portalRoutes.getScholarshipInfo,
{
headers: { Authorization: `JWT ${token}` },
}
);
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json().then((data) => ({ data }));
};
Here's the prefetched useQuery invocation:
await queryClient.prefetchQuery("portal", () =>
getScholarshipInfoSSR(token)
);

send json via paypal.request.post() from PayPal checkout.js

paypal.Button.render({
payment: function() {
var booksPurchaseRequest = {};
booksPurchaseRequest.amount = 20;
return paypal.request
.post(CREATE_PAYMENT_URL, JSON.stringify(booksPurchaseRequest))
.then(function(data) {
return data.paymentId;
});
}
}, '#paypal-button');
In such approach on back-end server I'm receiving data in application/x-www-form-urlencoded format, but I need application/json. How can I achieve that? Can paypal.request.post() be replaced with simple $.ajax()?
return paypal.request({
method: 'post',
url: '/foo/bar',
json: {
foo: 'bar'
}
}).then(function(response) {
})
Or you can just use jQuery, you just need to return a promise

How to dynamically read external json files in node.js?

I am creating a website that reads externally hosted json files and then uses node.js to populate the sites content.
Just to demonstrate what I'm after, this is a really simplified version of what I'm trying to do in node.js
var ids = [111, 222, 333];
ids.forEach(function(id){
var json = getJSONsomehow('http://www.website.com/'+id+'.json');
buildPageContent(json);
});
Is what I want to do possible?
(Marked as a duplicate of "How do I return the response from an asynchronous call?" see my comment below for my rebuttal)
You are trying to get it synchronously. What you should aim for instead, is not a function used like this:
var json = getJSONsomehow('http://www.website.com/'+id+'.json');
but more like this:
getJSONsomehow('http://www.website.com/'+id+'.json', function (err, json) {
if (err) {
// error
} else {
// your json can be used here
}
});
or like this:
getJSONsomehow('http://www.website.com/'+id+'.json')
.then(function (json) {
// you can use your json here
})
.catch(function (err) {
// error
});
You can use the request module to get your data with something like this:
var request = require('request');
var url = 'http://www.website.com/'+id+'.json';
request.get({url: url, json: true}, (err, res, data) => {
if (err) {
// handle error
} else if (res.statusCode === 200) {
// you can use data here - already parsed as json
} else {
// response other than 200 OK
}
});
For a working example see this answer.
For more info see: https://www.npmjs.com/package/request
I think problem is in async request. Function will return result before request finished.
AJAX_req.open( "GET", url, true );
Third parameter specified async request.
You should add handler and do all you want after request finished.
For example:
function AJAX_JSON_Req( url ) {
var AJAX_req = new XMLHttpRequest.XMLHttpRequest();
AJAX_req.open( "GET", url, true );
AJAX_req.setRequestHeader("Content-type", "application/json");
AJAX_req.onreadystatechange = function() {
if (AJAX_req.readyState == 4 && AJAX_req.status == 200) {
console.log(AJAX_req.responseText);
}
};
}

Pass a value from controller as JSON in codeigniter to view that contain on Angular Js

I need to use this:
http://demos.telerik.com/kendo-ui/multiselect/angular
but my problem when I try to change the url to:
read: {
url: base_url+"index.php/welcome/findAll",
}
and the function findAll in controller contain on:
public function findAll()
{
$listproduct = $this->mproduct->findAll();
echo json_encode($listproduct);
}
The list of options become empty.
You controller seems to be fine as long as it returns a valid JSON format.. in your AngularJS controller try doing:
$scope.MyFunction = function()
{
console.log("posting data....");
$http({
method : 'GET',
url : 'http://domain/controller/method_that_return_json',
headers: {'Content-Type': 'application/json'},
data : JSON.stringify({What you want to return from JSON here})
}).success(function(data) {
console.log(data);
});
}
Another aproach:
$http.get("http://www.domain.com/pathtojson)
.success(function(response) {
$scope.related = response;
});
}

Angular factory does not return array of objects but a single object

I am new to angular and I am trying to load a CSV list inside a factory and then convert it to json. I am using Papaparse (CSV to json library) inside the factory. When I console log the factory I get the array of objects which is exactly what I want but when I pass it inside my controller I get a single object which holds all the data.
This is my factory
(function() {
var app = angular.module('test');
app.factory('testFactory', ['$http', function($http) {
var url = 'my-list.csv';
var getContact = function() {
return $http.get(url).success(function(data) {
Papa.parse(data, {
header: true,
complete: function(results) {
console.log(results.data);
return results.data;
}
});
});
};
return {
getContact: getContact
};
}]);
}());
And this is my controller
(function() {
var app = angular.module('test');
app.controller('testCtrl', ['$scope', 'testFactory', function($scope, testFactory) {
testFactory.getContact().then(function(data) {
$scope.contacts = data;
console.log(data);
});
}]);
}());
I want be able to do something like this inside my view
{{ contact.firstname }}
The issue is the order of resolution. Inspecting the console statements shows that you're assigning $scope.contacts to the resolution of the $http.get promise, and not the actual parsing.
Instead of returning the $http.get promise, return a deferred promise and resolve at the end of parsing:
var parsePromise = $q.defer();
$http.get(url).success(function(data) {
Papa.parse(data, {
header: true,
complete: function(results) {
console.log(results.data);
parsePromise.resolve(results.data);
}
});
});
return parsePromise.promise;
See working demo here.
Update: As per the comments, you could use .then to chain promises instead of creating a new deferred. The plunkr has both, you can use the changelog to toggle methods.