【发布时间】:2020-09-13 11:49:14
【问题描述】:
我正在尝试制作一个下载按钮,用于下载页面中显示的 Json 文件的特定部分。 我一直在使用很多方法,这里的这个似乎非常好:How to create and download text/Json File with dynamic content using angular 2+ 但实际上,它只下载我的 json 文件的一部分,而不是其他取决于路线的文件。让我解释。 这是我使用我看到的解决方案制作的 TS:
propertyKey: Property;
constructor(
private route: ActivatedRoute,
public router: Router,
) { }
ngOnInit() {
this.propertyKey = this.route.snapshot.data['propertyKey'];
}
JsonData() {
return of({
rule: this.propertyKey.rule,
cdfRule: this.propertyKey.cdfRule,
compiledRule: this.orgaCompiledRule,
snippet: this.propertyKey.snippets,
cdfSnippet: this.propertyKey.cdfSnippets,
all: this.propertyKey
});
}
private setting = {
element: {
dynamicDownload: null as HTMLElement
}
}
dynamicDownloadTxt() {
this.JsonData().subscribe((res) => {
this.dyanmicDownloadByHtmlTag({
fileName: 'My Report',
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);
}
}
在模板中:
<div *ngIf="router.isActive('orga-data-model/property/jsondisplay/rule', false)" [appJsonFormatter]="propertyKey.rule">
<div style="text-align-last: right; margin-right: 10px; padding-top: 10px;">
<a style="font-size: 1.5em;" (click)="dynamicDownloadTxt()">Download Json</a>
</div>
</div>
<div *ngIf="router.isActive('orga-data-model/property/jsondisplay/cdfruleorga', false)" [appJsonFormatter]="propertyKey.cdfRule">
<div style="text-align-last: right; margin-right: 10px; padding-top: 10px;">
<a style="font-size: 1.5em;" (click)="dynamicDownloadTxt()">Download Json</a>
</div>
<div *ngIf="propertyKey.cdfRule === null || !propertyKey.cdfRule">No Data</div>
</div>
所以,在我的模板中,显示 json 不是问题。它工作得很好。当我想下载显示在特定 url 中的那部分 json 时,它不起作用,它总是下载相同的 Json。 谁能帮我?谢谢。
【问题讨论】:
-
你能分享一下这个问题的堆栈吗?
-
这会很困难,有很多不同的服务可以让 json 工作并显示出来。但这里的问题是如何使 jsonData 函数成为动态的,并且只引用路由上的数据,而不是函数中声明的数据。否则,我想我总是会收到相同的数据。
标签: javascript json angular