Home > Back-end >  Downloading a json file (from json-server) as a txt or json or csv file, in an Angular app
Downloading a json file (from json-server) as a txt or json or csv file, in an Angular app

Time:10-13

I have installed the json-server in my Angular app which enables me to save a form (filled by the user) via a fake json API into a json file:

{
  "extracts": [
    {
      "contentName": "xxx",
      "contentType": "xxx",
      "contentToStore": "xxx",
      "id": 1
    }
  ]
}

I can also see the results at my http://localhost:3000/extracts

In my html template, my form is submitted:

<form #postForm="ngForm" (ngSubmit)="onSubmitExtractions(postForm.value)">

In the corresponding component, I have written this code:

onSubmitExtractions(postData: Post) {
    
    this
      .dbService
      .submitExtractions(postData)
      .subscribe(
        postData => {
          this.jsonPosts.push(postData);
        }
    );
    
    this
      .dbService
      .downloadExtractions(postData);
}

The first snippet writes to the json file, with this code in the service script:

submitExtractions(post: Post): Observable<Post> {
    return this.httpClient.post<Post>(this.apiUrl, post, httpOptions);
}

This works fine and I get the results in a json file (fake json server database) and the second snippet is supposed to download this file whose code in the service script is this:

downloadExtractions(post: Post) {

    const blob = new Blob([JSON.stringify(post, null, 2)], { type: 'application/json' });

    if (blob) {
      this.downloaded = 'The blob contains '   blob.size   ' byte!';
    } else {
      this.downloaded = 'The download failed!';
    }
}

What am I missing in ths code in order to actually download the json content? How do I download this content as a csv or json or even a text file?

p.s. Here are a few screenshots that show the same structure I have described above:

enter image description here

enter image description here

enter image description here

enter image description here

CodePudding user response:

Please try this solution. It is using the same blob just with some constant data.

in html

<a [href]="fileUrl" download="file.txt">DownloadFile</a>

in component.ts

export class AppComponent implements OnInit {
  name = 'Angular 5';
  fileUrl;
  constructor(private sanitizer: DomSanitizer) {  }
  ngOnInit() {
    const data = 'some text';
    const blob = new Blob([data], { type: 'application/octet-stream' });

    this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
  }

}

For reference, please visit:

https://stackblitz.com/edit/angular-blob-file-download-text-file?file=app/app.component.ts

  • Related