Download a file from API using Angular 2+

 In this post I'm going to explain to download a file using angular framework. For this solution I’m using angular 9 this is valid for all 2+ versions of angular.

Installation

 

Install a library in the application using npm.

 

npm install file-saver --save

This library is working fine with below mentioned browsers: -

  • Google Chrome
  • Microsoft Edge
  • Opera 12+
  • Firefox 3.5+
  • Safari 6+
  • IE9+

Service

We need to create a service to create download function using file saver library. Once we have created the service we need to register it under the app.module.ts file inside the @NgModule decorator.

But if you are register your service under the @NgModule these can be used anywhere in application.

When the service is provided at root level, Angular creates a single, shared instance of service and injects into any class that needs it. Registering the provider in the @Injectable metadata also allows Angular to optimize an application by removing the service if it is not used.

Service code: - 

import {Injectable} from '@angular/core';

import {HttpResponse} from '@angular/common/http';

import {Http, ResponseContentType} from '@angular/http';

import {Observable} from 'rxjs';

@Injectable({ providedIn: 'root' })

export class FileService {

  constructor(private http: Http) {}

  download(): any {

        return this.http.get('http://localhost:4200/api/epaper', { responseType: blob });

}

}

In Component Section:-

download() {

    this.fileService.download().subscribe(response => {

let blob:any = new Blob([response], { type: 'text/json; charset=utf-8' });

const url = window.URL.createObjectURL(blob);

fileSaver.saveAs(blob, 'epaper.json');

}), error => console.log('Error downloading the file'),

                 () => console.info('File downloaded successfully');

  }

You just need to call the download function from HTML and you are able to download the file easily.

Hope you like the post☺


    Post a Comment

    2 Comments