gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:01:50 27 4
gpt4 key购买 nike

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


}


}

最佳答案

这种方法对我有用。确保从文件保护程序导入 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

关于angular - 无法读取未定义的属性 'saveAs',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46670218/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com