"Learn the process of extracting information from a database and exporting it to a CSV file with Angular 2

Currently, I am facing an issue where I need to retrieve data from a database and export it to a CSV file. While I am able to fetch all the data successfully, I am encountering difficulty when trying to fetch data that is in object format as it shows up as "[object object]" in the CSV file.

TS file:

getData() {
   let source = this.resultList;
   let destination = [];
     for (let i = 0; i < source.length; i++) {
         let entry = new Entry();
         entry.id = source[i]['id'];
         entry.participantId = source[i]['participantId'];
         entry.completedOn = moment(source[i]['completedOn']).format('DD/MM/YYYY');
          if (typeof source[i]['satisfaction'] == 'string') {
              entry['satisfaction'] = source[i]['satisfaction']
            } else {
                for (var property in source[i]['satisfaction']) {
                    if (source[i]['satisfaction'].hasOwnProperty(property)) {
                     entry[property] = source[i]['satisfaction'][property]
                    }
            }
          }
         destination.push(entry);
     }
     return destination;
    }

I am struggling to extract objects present in "prodandService" to the CSV file - they are being displayed as "[object object]" instead of the actual items.

JSON data:

{"satisfaction":{"prodandService":[{"index":"Orbiz"},{"index":"qwerq"},{"index":"asfd"},{"index":"test"},{"index":"test123"},{"index":"TestWD"},{"index":"IOS app"},{"index":"Lipstick"},{"index":"Foundation"},{"index":"lipstick"},{"index":"Website"},{"index":"App IOS"},{"index":"Shampoo Vanilla"},{"index":"Shampoo Strawberry"},{"index":"car"},"Lipstick"],"price":"medium","customer":"yes","recomondation":"4","sales":["phone"],"phoneVist":"3","importance":["Quality"],"frequence":"quarter","satisfaction":"3"},"completedOn":"2017-08-28T09:39:54.676Z","id":10,"participantId":217}

I would greatly appreciate any assistance with this issue.

Answer №1

Utilizing a library for exporting to CSV files proved to be highly effective for me:

In my Angular4 application, I have incorporated an external library for document exportation: https://github.com/eligrey/FileSaver.js/

Below is the excerpt of code I implemented to extract my data. I linked this method to a button for triggering the event:

TypeScript component : (EDITED)

  // Pay attention to the parameters received from the service call that provide the filtered data
  exportDatas(documentType: string) {
    // Presuming you have stored the service data you wish to export in this.resultList
    let source = this.resultList;
    const blob = new Blob([source.blob()]);
    const objectUrl = URL.createObjectURL(blob);
    FileSaver.saveAs(blob, 'Export.' + documentType);
  }

Template side : (EDITED)

<div>
  <button (click)="exportDatas('csv')" type="button">CSV</button>
  <button (click)="exportDatas('pdf')" type="button">PDF</button>
</div>

Functioning seamlessly, and the code is now easier to maintain.

EDIT :

Installation via NPM :

  • npm install file-saver --save
  • npm install @types/file-saver --save-dev
    (Adding types if required, although not utilized by me)

Ensure to import it into your component (particularly when using Angular-CLI) :

  • Without types :
    import * as FileSaver from 'file-saver';
  • With types (not tested but should work) :
    import { FileSaver } from 'file-saver';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to define 'this' context and reference an instance of an Angular 6 component?

I have successfully created a demo featuring an Earth globe using D3 and JS. Now, I am exploring the process of transforming it into an Angular 6 component. Below is the full demo without Angular: import * as d3 from 'd3v4'; import { Component ...

The functionality of jQuery's appendTo method seems to be malfunctioning

I am trying to display an image with a popup using jQuery mobile. In my loop, I have the code below: for( var i = 0; i < imageArray.length; i++ ) { counter ++; // Create a new Image element var img = $('<img data-rel="popup" class=" ...

Why isn't my Promise fulfilling its purpose?

Having trouble with promises, I believe I grasp the concept but it's not functioning as expected in my project. Here is a snippet of my code : (I am working with TypeScript using Angular 2 and Ionic 2) ngOnInit() { Promise.resolve(this.loadStatut ...

Issue with the onClick event in next.js and TypeScript

While working on the frontend development of an app, I encountered a strange issue with the onClick function. The error message I'm seeing is: Type '(e: SyntheticEvent<Element, Event>) => void' is not assignable to type 'Custom ...

The Angular Date Pipe is displaying an incorrect date after processing the initial date value

Utilizing Angular's date pipe within my Angular 2 application has been beneficial for formatting dates in a user-friendly manner. I have successfully integrated API dates, edited them, and saved the changes back to the API with ease. However, an issue ...

An effective way to extract targeted information from an array of objects using Typescript

I'm having trouble extracting the IDs from the selected items in my PrimeNG DataTable. Despite searching on Google, I couldn't find much information about the error I'm encountering... ERROR in C:/Users/*****/Documents/Octopus/Octopus 2.0/s ...

Discover the method for inserting a title attribute value into a span element

Utilizing AngularJS to retrieve and display data within a span element. I am now aiming to utilize this value as the title for another span element. The current code being used is shown below: <span style="display: inline-block; width: 160px">{{acti ...

The form in ReactJs is not functioning properly as it is not properly connected, despite containing only a

When attempting to create a form to add a new item into an array, I encountered the error message: Form submission cancelled because form is not connected. Despite finding some suggestions to change the submit button type from "submit" to "button", it did ...

Issue with clientHeight not functioning properly with line breaks in Angular 2 application after ngAfterViewInit

I have successfully created a Gridify page in my Angular 2 application using the Gridify library. To initialize it, I've utilized a custom ngAfterViewChecked method: ngAfterViewChecked() { var selector = document.querySelector('.read-grid& ...

Ways to assign the value of an alert to an element

Within this piece of code, my intention is to retrieve the alert value and apply it to an element. Description: The AJAX code I have written checks for values in a database, fetches new values from the database, and then displays these fetched values in a ...

Restore font-weight if a different list item is chosen

I previously inquired about setting the font-weight to bold on a text element when selected. Thanks to @Eric, this has been successfully implemented! However, I am facing an issue where clicking on one text makes it bold, and then clicking on another text ...

How to import a module from the root path using TypeScript in IntelliJ IDEA

Despite this topic being widely discussed, I still struggle to understand it. Below is my tsconfig.json file: { "compilerOptions": { "module": "commonjs", "target": "es2017", "sourceMap": true, "declaration": true, "allowSyntheticDe ...

Exploring the `React.createRef` method using Enzyme for testing purposes

Is there a way to test the following class that utilizes the React.createRef API? I couldn't find any examples online. Has anyone attempted this before? How can I mock the ref effectively? My preference would be to utilize shallow. class Main exten ...

Trouble with binding to an array inside a Vue component instance

Trying to grasp the concepts of vue.js, but struggling with a crucial element. The goal is to create an accordion functionality for multiple boxes (only one box displayed at a time; opening a new box closes any previously open ones). Here's the curre ...

Is Dealing with Multiple AJAX Requests a Pain?

Currently, I am utilizing AJAX to retrieve a list of active streams from TwitchTV along with their viewers, updating every second. Sometimes the stream list can become quite long, so my plan is to divide the AJAX requests into 2 or 3 parts: 1) Obtain Numb ...

In order to properly execute the JavaScript code, it is essential to create a highly customized HTML layout from the ER

I am currently utilizing this resource to create a gallery of images on my Rails page. Here is the HTML code required to display the images: <a href="assets/gallery/ave.jpg" title="Ave" data-gallery> <img src="assets/gallery/ave_tb.jpg" alt="Av ...

Multi-line D3 chart that dynamically updates and intersects with the axis

I am attempting to create a multiline d3 chart that can be updated with new datasets. I have developed a method to plot the new data on the existing d3 frame, but I am encountering issues when trying to update the chart with mocked data. The new data is no ...

The name is not found when using attribute, but it is found when using extends

Lately, I've encountered difficulties with creating large TypeScript modules, and there's one thing that has been puzzling me. Specifically, the following scenario doesn't seem to work: // file A.ts export = class A { } // file main.ts imp ...

Implement pagination for API calls within a React Component

I am trying to implement pagination for the results of an API call. The following code snippet shows how I am making the API call using Axios: apiCall() { const API = `http://www.omdbapi.com/`; axios.get(API, { params: { apikey: proces ...

Processing JSON Serialization from Controller to AJAX Response

I'm struggling to find the correct way to use an HttpWebRequest, and then convert its response into a readable format of JSON for a JavaScript AJAX function. If I just return the raw text, it includes escaping slashes in the response. If I deserializ ...