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");
}
}