Exporting a UI data to the Server Side using Angular2 typescript - json

I have a table in the UI with the data. I want to export that data to the api side( restful service) in the csv format ( or json format, later I can convert that to the csv format on server side) so that I can download the file to provide a report.
I have a data as below as in the attachment:
I want all the table data to to be stored in an object and pass that object to the service side as a URL(using a POST request).
And I need to download that data on the server side( For this I have written a code to convert a JSON data to CSV form and then exporting it )
Have google for it and all I came across is the .js files and functions for it.while I am using/need typescript.
can I get a code snippet for it or at-least how to approach for a solution.
thanks in advance for the response.

You can export data (assuming that you have the list of data ) as Json object using http module, here the code that should do the work:
exportData(dataList : any): Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.serverApiUrl, JSON.stringify(dataList), options)
.map(res => {
return res.json();
});
}

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

Convert data from XML to JSON React.js

Im trying to build an application that fetches data from an web API that returns XML. I want this data in JSON instead, but the API does not support that.
How do i fetch the data and convert it to JSON?
I tried to use xml2js and it seems to work, but i dont understand how to save it as an object so i can use it in my app.
async componentDidMount(){
const url = "this is where the APIurl are";
fetch(url)
.then(res => res.text())
.then(body => parseString(body, function (err, result) {
console.log(result);
})
);
}
result seems to return the data as json, but i cant figure out how to use the data as an object later.
Your best option is to use an external lib to do that. A quick search in google and I found this one https://www.npmjs.com/package/xml-js.
You should also check this question: Convert XML to JSON (and back) using Javascript
To store it on your app you should grab what you need from the parsed XML and put it on the state.

Sending multiple content type in single request

I'm trying to send multiple files with additional JSON data to the api. The api seems to support multiple content types.
How can i form the header with two content types
1. Multipart form data (for files)
2. application/json (for other json params)
Thanks to Jack's answer on https://stackoverflow.com/a/24535293/9404093, I set up the following using different content types:
uploadFile(request: FileUploadRequest, file: File): Observable<FileUploadResponse> {
const formData: FormData = new FormData();
formData.append('details', new Blob(
[JSON.stringify(request)],
{ type: "application/json" }
));
formData.append('file', file, file.name);
formData.append('contentType', file.type);
return this.http.post<FileUploadResponse>(FILES_URI, formData);
}
By using a Blob, you can assign a content type to the blob content (json).
Note this works with a Java Spring backend controller as well:
#PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> upload(#RequestPart FileUploadRequest details, #RequestPart MultipartFile file) {
// TODO: the stuff
}

ReactJS: Unable to send JSON data and PDF file in one POST call

I am working on GRAILS-ReactJs based project which involves a scenario where I need to send the RESUME and the JSON data in one POST call.
However, I am able to send file in one call but the data I am getting is null.
I am using Grails-3 at my server side and receiving the POST request as multipart file. I want both JSON and Multipart file object to be combined in one object to send to the server and want to receive the file and the JSON data both at the server side.
I have tried changing the content type of the header but ut doesn't work.
You can't post JSON data along with the file or any other attachment. You can post it as form data to your back end. The form data is passed as a multi-part data to the server with relevant boundaries. Here's a sample code for your reference. You may pass json data along with the formData as key, value pairs.
export function postAttachment (fileData, fileName) {
let formData = new FormData()
formData.append('prop1', 'value1')
formData.append('prop2', 'value2')
formData.append('upload', fileData, fileName)
return fetch('/your/endpoint', {
headers: {
'Accept': 'application/json',
'header1': 'headerValue1'
},
method: 'POST',
body: formData
})
}
Hope this helps. Happy Coding !

How to update json file in AngularJS

I want to update the existing json file in AngularJS
JSON file:
{
"text1": "Click here to edit!",
"text2": "Click here to edit!",
"text3": "Click here to edit!",
"text4": "Click here to edit!"
}
I want to update this JSON file as:
text1: "Abc"
and save this changes in JSON file
You can not update a json file without using a server-side language like PHP or python. Basically it is security compliance. For more understanding kindly go through
https://docs.angularjs.org/guide/security
https://docs.angularjs.org/api/ng/directive/ngCsp
and
https://developer.mozilla.org/en-US/docs/Web/Security/CSP
Imagine you have getjson.php and savejson.php in the server which work exactly as their names suggest.
Now use $http service of Angular to retrieve your json from the server.
$http.get("getjson.php").then(function(response){
$scope.myJsonObject = response.data;
//Your json becomes JS object here. Change it the way you want
$scope.myJsonObject.text1 = "Abc";
});
Use $http service again to send your json back to the server.
$http({
method: "post",
url: "savejson.php",
data: $scope.myJsonObject,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
This is the basic. Please note that you need to do your php part to save/load your json file. Also you should handle errors of the $http service.
Please see how $http service and promises work.