Search code examples
angularangular2-services

Writing HTTP response in the CSV file with angular 2


In my angular application I am getting the http response where, lets say the response body contains below data.

var data =
        {
            "name": "Test 1",
            "age": "13",
            "average": "8.2",
            "approved": "true",
            "description": "using 'Content here, content here' "
        };

then I have to write this is CSV file for which I am using angular2csv library as below:

new Angular2Csv(data, 'My Report');

This is writing some junk characters in the excel. but if I pass the data as below it is working as expected.

var dataNew =[
        {
            "name": "Test 1",
            "age": "13",
            "average": "8.2",
            "approved": "true",
            "description": "using 'Content here, content here' "
        }];

how to convert data in the same structure as datanew ?


Solution

  • The only difference between data and dataNew is that former is an object, while latter is an array.

    To make things work, you can return array element from API else you can create new temporary array variable like below at client side:

    var data =
        {
            "name": "Test 1",
            "age": "13",
            "average": "8.2",
            "approved": "true",
            "description": "using 'Content here, content here' "
        };
    var dataArray = new Array<any>();
    dataArray.push(data);
    new Angular2Csv(dataArray, 'My Report');
    

    Hope it helps!!