Search code examples
htmljsonangulartypescriptjson-server

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


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?


Solution

  • 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%2Fapp.component.ts