无法读取未定义的属性'saveAs'

时间:2017-10-10 15:12:27

标签: angular filesaver.js

我希望能够在Angular组件中创建和下载文件。为了做到这一点,我正在使用FileSaver.js。即使我已在我的组件中导入它,我在控制台中收到此错误:

ERROR TypeError: Cannot read property 'saveAs' of undefined

这是我的组成部分:

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


}


}

2 个答案:

答案 0 :(得分:1)

这种方法对我有用。确保从文件保护程序导入saveAs并将其另存为文件。因此,在顶部,您将拥有:

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

因此在FileSaver.saveAs上使用saveAs

答案 1 :(得分:0)

使用您的构造函数声明您的FileSaver,以便能够使用它

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

}

然后只使用fs变量。应该工作