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");
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With