我想在Typescript中创建自己的下载类。 这就是它现在的样子:
export class Download {
private _name: string;
constructor() {
this._name = "";
}
public get name(): string {
if (this._name !== "") {
return this._name
} else {
return "empty";
}
}
public set name(new_name: string) {
this._name = new_name;
}
public download(data: string) {
let encodedUri = encodeURI(data);
let link: HTMLAnchorElement = <HTMLAnchorElement> document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", this._name);
<HTMLAnchorElement> document.body.appendChild(link);
link.click();
}
}
但是当我想执行此操作时,我收到此错误:ReferenceError:文档未定义。
我做错了什么?
提前致谢^^
答案 0 :(得分:-1)
如果您将以下代码粘贴到documentation中,则可以正常使用。 因此,您的代码似乎在节点范围内执行,其中文档不可用。
class Download {
private _name: string;
constructor() {
this._name = "testing";
this.download("test.html");
}
public download(data: string) {
let encodedUri = encodeURI(data);
let link: HTMLAnchorElement = <HTMLAnchorElement>document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", this._name);
document.body.appendChild(link);
link.click();
}
}
let d = new Download();
话虽如此,我不确定创建一个不可见的链接,然后以编程方式单击它是下载文件的推荐方法:)