无法读取未定义的属性“saveAs”

eli*_*eli 4 filesaver.js angular

我希望能够在 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");


}


}
Run Code Online (Sandbox Code Playgroud)

小智 7

这个方法对我有用。确保从文件保护程序导入 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");
}
Run Code Online (Sandbox Code Playgroud)

所以在 FileSaver.saveAs 上使用 saveAs