What is the alternative method for converting an API stream into a .csv file without relying on FileSaver or createObjectURL()?

These are the only two methods currently available.

An issue with createObjectURL() is that it is deprecated and cannot be called in Chrome anymore.

Using FileSaver may feel like adding unnecessary complexity to your project when it should be a simple task in Angular.

This is where I am currently:

const params = {'params' : p};
const httpOptions = this.authenticationService.getRequestOptions();
httpOptions['responseType'] = 'text/csv';

this.http.post(
  this.url + this.currentId,
  params,
  httpOptions
).subscribe((response: any) => {
  console.log(response);
  const blob = new Blob([response], {type: 'text/csv'});

  const link = document.createElement('a');
  link.setAttribute('style', 'display: none');
  link.href = response; // should be a URI but document.URL.createObjectURL() is deprecated
  const date = new Date();
  link.download = 'file.csv';
  link.click();
  link.remove();
}, error => {
  console.log('I failed :(', error);
}); 

The above code successfully downloads a file, but the issue of converting the blob to a URI remains unsolved.

Update for Clarity:

As of today, 19/11/2019, and since 1/11/2017, window.URL.createObjectURL is deprecated and will return an error. Click here for more information.

I came across this information:

More information on HTMLMediaElement.srcObject

Code examples related to srcObject

Discussion on deprecation of createObjectURL and introduction of HTMLMediaElement.srcObject

While it is supposed to replace createObjectURL, it seems to work only for video elements.

Answer №1

After some exploration and experimentation, I managed to find the solution. It was a pleasant surprise to discover how easy it is to download a file even after the deprecation of createObjectURL(). Here is the code snippet that made it possible:

this.http.post(
  this.url + this.currentId,
  params,
  httpOptions
).subscribe((response: any) => {
  const link = document.createElement('a');
  link.setAttribute('style', 'display: none');
  link.href = 'data:attachment/csv,' + encodeURI(response); // <- it was as simple as this.
  const date = new Date();
  link.download = this.currentChoice + '-' + date.getDate() + '-' + (1 + date.getMonth()) + '-' + date.getFullYear() + '.csv';
  link.click();
  link.remove();
}, error => {
  console.log('File download failed : ', error);
});

Since my API's response already contains the raw content of the file, there is no need for me to use .text() or any other methods.

I hope this explanation proves helpful :)

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

Issues with Tracking File Progress through PHP and AJAX!

Hey there, I'm not the best at explaining things, so please be patient with me.. I am trying to figure out how to create a status/progress bar in PHP that shows the percentage of a text file being read/parsed. I have an idea of counting lines or usin ...

Guide on deploying an Angular 7 frontend paired with a Spring Boot backend

Having trouble with integrating my Angular application with Spring Boot REST backend. Can anyone suggest a simple method to run both on the same localhost port? ...

Retrieving the innerHTML or innerText of a structural DOM element generated by *ngFor in Selenium

Having trouble accessing the innerHTML/innerText of a structural DOM element, only getting a commented element instead of the child elements. <div class="snap-box"> <label class="snap-heading">Recommendations</label> <div class="r ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

Angular 2 Mastering the Art of Saving State in Routing with Precision

I have been working on a search page that retains users' search criteria even after navigating away from the page. I came across a helpful resource at that enabled me to achieve this functionality successfully. However, I encountered an issue where ...

How to Install Definitely Typed Packages in Visual Studio 2015 RC for AspNet5 with the Help of Gulp and TSD

Struggling to add angular.d.ts to my MVC6 project, I've hit a roadblock. Although I've configured Gulp to reinstall necessary packages using tsd, I'm stuck on the initial installation process. The instructions suggest running 'tsd inst ...

Unable to send a function as props to a child component in TypeScript

Within my application, I have a parent component that holds a state and a setState function. This state and function are then passed down to a child component in order to retrieve values (such as input field data). When the function is triggered in the chi ...

Problem with dynamic page routes in Next.js (and using TypeScript)

Hi everyone, I'm currently learning next.js and I'm facing an issue while trying to set up a route like **pages/perfil/[name]** The problem I'm encountering is that the data fetched from an API call for this page is based on an id, but I wa ...

How do I assign a default value to an optional parameter in a derived class in Typescript?

One of my classes is called ClientBase: export class ClientBase { constructor(private uri: string, private httpClient: HttpClient) { } // Contains Various Methods } I have multiple subclasses that are derived from the ClientBase For instance: @I ...

An insightful guide on effectively binding form controls in Angular using reactive forms, exploring the nuances of formControlName and ngModel

Here is the code snippet: list.component.html <form nz-form [formGroup]="taskFormGroup" (submit)="saveFormData()"> <div nz-row *ngFor="let remark of checklist> <div nz-col nzXXl="12" *ngFor="let task of remark.tasks" styl ...

Limit the elements in an array within a specified range of dates

Currently, I am working on implementing a filter functionality for a data array used in a LineChart within my Angular application using TypeScript. The structure of the data array is as follows: var multi = [ { "name": "test1", "series": [ ...

update component following an ajax request

I attempted the suggested solutions for similar questions, however, they proved ineffective. Upon inserting data into my database, I am looking to update my component (with the user remaining on the same component). I tried navigating directly to the com ...

Query executed but no results returned

Currently, I am practicing GQL and facing an issue when trying to display data in the Playground. I am attempting to access the jsonplaceholder API to fetch all posts and show them, but encountering the following error: Error: GRAPHQL_FORMAT_ERROR: Expec ...

The typings for object properties in Typescript

I recently encountered a function call in my code: var myVar = myFunction({ property: 'prop', functionProperty() { console.log(this.property); }, functionProperty2() { this.functionProperty(); } }); I' ...

A series of OR interfaces in TypeScript Interface

Imagine a scenario where there is a choice between multiple interfaces interface a {x:string} interface b {y:string} interface c {z:string} type all = a | b | c Now, consider an object fulfilling all by being of type c When you try to access the propert ...

Specialized typescript function that is compatible with extended interfaces

Is there a way to create a versatile function that can be applied to any interface derived from a top-level interface? This function should take an unpersisted interface (without an id property) and return a persisted one (with an id property). The two ma ...

Troubleshooting Problem with Kendo UI Integration in Angular 2

Attempting to follow the steps outlined in http://www.telerik.com/kendo-angular-ui/getting-started/ Encountered this error message in the browser console. No errors found on the server side. <button kendoButton (click)="onButtonClick()" [ERROR ->][ ...

Resolve the issue of text overlapping on an image when zooming in

There seems to be an issue with overlapping text and images when zooming the page. I have included a screenshot for reference, please take a look and provide a solution. Thank you in advance.https://i.sstatic.net/oVlGN.png Here is the CSS code causing the ...

Error encountered numerous times within computed signals (angular)

I have incorporated signals into my Angular application. One of the signals I am using is a computed signal, in which I deliberately introduce an exception to see how it is handled. Please note that my actual code is more intricate than this example. pu ...

Angular2 and the Use of Environment Variables

I am working on an angular 2/4 app with a node server.js to serve it. I need to access an environment variable for switching between backend endpoints (using localhost for dev and another endpoint for prod). Both the frontend and backend apps are destined ...