在这里我想知道如何创建一个文本文件或 json 文件并下载它与将要填充的动态数据。
下面是我的
服务代码
validateUserData(userId) {
var headers = new Headers();
return this.http.get(`${this.baseUrl}/Users?userId=`+userId,{headers: headers}).map(result => {
return result.json();
});
}
component.ts
this.service.validateUserData(userId).subscribe( res => {
console.log(res);
new Angular2Txt(res, 'My Report');
});
在这里,我想将Response发送到我必须创建的文本文件或json文件,以便用户能够下载我该怎么做 Angular package
我试过上面的包,但我只能下载空文件
最佳答案
它不需要使用任何包,试试这个
@Component({
...
})
export class AppComponent {
private setting = {
element: {
dynamicDownload: null as HTMLElement
}
}
fakeValidateUserData() {
return of({
userDate1: 1,
userData2: 2
});
}
//
dynamicDownloadTxt() {
this.fakeValidateUserData().subscribe((res) => {
this.dyanmicDownloadByHtmlTag({
fileName: 'My Report',
text: JSON.stringify(res)
});
});
}
dynamicDownloadJson() {
this.fakeValidateUserData().subscribe((res) => {
this.dyanmicDownloadByHtmlTag({
fileName: 'My Report.json',
text: JSON.stringify(res)
});
});
}
private dyanmicDownloadByHtmlTag(arg: {
fileName: string,
text: string
}) {
if (!this.setting.element.dynamicDownload) {
this.setting.element.dynamicDownload = document.createElement('a');
}
const element = this.setting.element.dynamicDownload;
const fileType = arg.fileName.indexOf('.json') > -1 ? 'text/json' : 'text/plain';
element.setAttribute('href', `data:${fileType};charset=utf-8,${encodeURIComponent(arg.text)}`);
element.setAttribute('download', arg.fileName);
var event = new MouseEvent("click");
element.dispatchEvent(event);
}
}
<a (click)="dynamicDownloadTxt()" >download Txt</a>
<a (click)="dynamicDownloadJson()" >download JSON</a>
关于angular - 如何使用 angular 2+ 创建和下载具有动态内容的文本/Json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51806464/