Search code examples
angularobservable

Angular Observable data to csv


How can you generate a CSV file from a observable

download() {
  //const replacer = (key, value) => value === null ? '' : value;
  const header = 'Name;age;FavouriteFruit';
  const csv = this.persons$; 
  // How can I can I map the Observable data to csv lines.
  // This wil be an array of persons with the the properties age name and an array of 
  //fruits (string[])
  
  csv.unshift(header.join(',');
  const csvArray = csv.join('\r\n');

  const a = document.createElement('a');
  const blob = new blob([csvArray], { type: 'text/csv' });
  const url window.URL.createObjectURL(blob);

  a.href = url;
  a.download = 'fruit.csv';
  a.click();
  window.URL.revokeObjectURL(url);
  a.remove()
}

First of all I think I have to subscribe to the Observable and map the data but I am a little bit confused how I must map it to a csv format

data I receive when I log Persons$: [ { "name": "Babulaas", "Age": "88", "FavouriteFruits": [ { "name": "banana", "description": "happy yello fruit" } ] } ]


Solution

  • Yes, you indeed need to subscribe to the Observable to access its data, then transform that data into the CSV format.

        download() {
      // Header of the CSV file
      const header = 'Name,Age,FavouriteFruit';
      
      // Subscribe to the Observable
      this.persons$.subscribe(persons => {
        // Map the data to CSV format
        const csvContent = persons.map(person => {
          // If you need to check null and join the fruits array into a string. Otherwise ignore this line of code.
          const fruits = person.favouriteFruit && person.favouriteFruit.length > 0 ? person.favouriteFruit.join(';') : '';
          return `${person.name},${person.age},${fruits}`;
        });
    
        // Combine the header and the content
        csvContent.unshift(header);
        const csvArray = csvContent.join('\r\n');
    
        // Create a Blob from the CSV String
        const blob = new Blob([csvArray], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
    
        // Create an anchor element and trigger the download
        const a = document.createElement('a');
        a.href = url;
        a.download = 'persons.csv';
        a.click();
    
        // Cleanup
        window.URL.revokeObjectURL(url);
        a.remove();
      });
    }
    

    This is just an example of what such a method could look like. I don't know the name of your observable or what structure it has. I'm basing this on the description in your example, but I doubt I'll hit exactly your structure, and many things can differ.

    I hope this helps you.