Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Filesaver js with angular2

i have checked all the post i can find on the use of Filesaver JS with angular, but i still could not wrap my head around a soution. I added this to the map section of my system.config.js

 'filesaver': 'node_modules/filesaver/src/Filesaver.js'

I added this to the packages section of the system.config.js

  'filesaver': {defaultExtension: 'js'}

I then imported it in my service.ts this way

import { saveAs } from 'filesaver';

Yet i get this error.

enter image description here

Can someone help please?

like image 974
mayowa ogundele Avatar asked Nov 24 '16 09:11

mayowa ogundele


1 Answers

Try the following

npm install file-saver --save

Then add a declarations file to your project like 'declarations.d.ts' and in it put

declare module 'file-saver';

In your systemjs.config.js, add the following to the map section

'file-saver': 'npm:file-saver/FileSaver.js'

And then import the library in your component or service like below

import { Component } from '@angular/core';
import * as saveAs from 'file-saver';


@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
  <button (click)="SaveDemo()">Save File</button>`,
})
export class AppComponent {
  name = 'Angular';

  SaveDemo() {
    let file = new Blob(['hello world'], { type: 'text/csv;charset=utf-8' });
    saveAs(file, 'helloworld.csv')
  }
} 

Hope it helps.

like image 150
dipole Avatar answered Sep 21 '22 03:09

dipole