4

I want to be able to create and download a file in an Angular component. In order to do that I'm using FileSaver.js. Even though I have imported it in my component, I get this error in console:

ERROR TypeError: Cannot read property 'saveAs' of undefined

This is my component:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FileSaver } from 'file-saver';


@Component({
moduleId: module.id,
templateUrl: 'home.component.html',
styleUrls: ['home.component.css']
})

export class HomeComponent implements OnInit {


constructor(private http: HttpClient) {

}

nodes: any;
ngOnInit(): void {
  // Make the HTTP request:
  this.http.get('assets/file.json').subscribe(data => {
    // Read the result field from the JSON response.
    this.nodes = data;
    this.saveFile();

  });

}

saveFile=function (){
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");


}


}
eli
  • 313
  • 3
  • 6
  • 17

2 Answers2

7

This method worked for me. Make sure you import saveAs from file-saver and use that to save as a file. So on the top you will have this:

import { saveAs } from 'file-saver';
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient, ) {}

saveFile=function (){
    var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
    saveAs(blob, "hello world.txt");
}

So use saveAs on FileSaver.saveAs

0

declare your FileSaver with your constructor to be able ot use it

constructor(private http: HttpClient, private fs : FileSaver) {

}

And then just use the fs variable. Should work

sheplu
  • 2,937
  • 3
  • 24
  • 21
  • You mean, I can use the fs variable like this: `this.fs.saveAs(...)`? – eli Oct 10 '17 at 15:18
  • I tried it, now I get another error: `Can't resolve all parameters for HomeComponent: ([object Object], ?).` – eli Oct 10 '17 at 15:21
  • 1
    In that case remove what you add in the component and try to import filesaver this way. `import * as FileSaver from 'file-saver';` – sheplu Oct 10 '17 at 16:29