When retrieving data from an API and attempting to parse it as JSON in Angular ts, the following error occurs: "Argument of type 'Subscription' is not assignable to parameter of type 'string'". The desired outcome is to receive the JSON response from the API in the format [{name:"name1"},{name:"name2"}] instead of [{"name":"name1"},{"name":"name2"}], as the latter does not properly write the name on the CSV file.
[HttpGet("getEmployees")]
[ProducesResponseType(200, Type = typeof(IEnumerable<EmployeesView>))]
public async Task<IActionResult> GetEmployeesByCreateDate(DateTime period)
{
try
{
// Read model returns users based on a logic as enumerable
return Ok(await _readModel.GetEmployees(period));
}
catch (Exception e)
{
// Throw exception
}
myService.ts
getAllPosts() {
return this.http.get<IEmployee[]>(this.URL).subscribe((data: any) => {return data;});
}
download(data, filename='data') {
let csvData=this.ConvertToCSV(data, ['name1','name2']);
let blob = new Blob(['\ufeff' + csvData],{type:'text/csv;charset=utf8;'});
let dwldLink = document.createElement("a");
let url = URL.createObjectURL(blob);
dwldLink.setAttribute("href", url);
dwldLink.setAttribute("download", filename + ".csv");
dwldLink.style.visibility = "hidden";
document.body.appendChild(dwldLink);
dwldLink.click();
}
ConvertToCSV(objArray, headerList) {
let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
let str = '';
let row = 'S.No,';
for (let index in headerList) {
row += headerList[index] + ',';
}
row = row.slice(0, -1);
str += row + '\r\n';
for (let i = 0; i < array.length; i++) {
let line = i + 1 + '';
for (let index in headerList) {
let head = headerList[index];
line += ',' + array[i][head];
}
str += line + '\r\n';
}
return str;
}
myComponent.ts
JsonData = JSON.parse( this.URL.getAllPosts());
download2(){ this.URL.download(this.JsonData, 'jsontocsv'); } //here is the problem
The desired formatting of the returned data is:
[{"name":"name1", "surname":"surname1"}, {"name":"name2", "surname":"surname2"}]
However, the current output appears as follows (the desired structure is needed for downloading as CSV):
[{"name":"name1", "surname":"surname1"}, {"name":"name2", "surname":"surname2"}]