I have array in the following format which i need to post to an API :
console.log(addserverList);
I want to pass this to a post method of api
const options = {headers: {'Content-Type': 'application/json'}};
return this.http.post( 'http://localhost:54721/api/BulkUpload/SaveBulkUploadData',addserverList,options)
I am able post to api, but the data passes is always showing as NULL
Model i structured like below:
Function to generate array
private extractData(res: Response) {
let csvData = res['_body'] || '';
let allTextLines = csvData.split(/\r\n|\n/);
let headers = allTextLines[0].split(',');
let lines = [];
for ( let i = 0; i < allTextLines.length; i++) {
// split content based on comma
let data = allTextLines[i].split(',');
if (data.length == headers.length) {
let tarr = [];
for ( let j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
}
this.csvData = lines;
// console.log(JSON.stringify(this.csvData));
this.saveBulkUpload();
}
Your JSON is an array of arrays. The method is expecting an array of objects which match the format of the AddServer
class.
Your JSON should look something like this:
[
{
"HostName": "Server1",
"Type1": "type1_1",
"Type2": "type1_1",
},
{
"HostName": "Server2",
"Type1": "type1_2",
"Type2": "type2_2",
}
]
Change to function
This has required some guesswork as I don't know the service contract which is feeding into the function but what needs to be changed is in the loop.
for ( let i = 0; i < allTextLines.length; i++) {
// split content based on comma
let data = allTextLines[i].split(',');
if (data.length == headers.length) {
let tobj = {};
tobj.HostName = data[0];
tobj.Type1= data[1];
tobj.Type2= data[2];
lines.push(tobj);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.