我正在使用angular 2.我想给功能下载JSON文件。Angular2导出/下载json文件
就像我有回应res = {bar:foo}那么我想创建json文件,它将包含这个响应,可以下载按钮/锚点击。
任何帮助将不胜感激。
我正在使用angular 2.我想给功能下载JSON文件。Angular2导出/下载json文件
就像我有回应res = {bar:foo}那么我想创建json文件,它将包含这个响应,可以下载按钮/锚点击。
任何帮助将不胜感激。
很简单的话,我在模板
<a class="btn btn-clear" title="Download JSON" [href]="downloadJsonHref" download="download.json"></a>
如何或何时generateDownloadJsonUri()调用 –
我已经在构造函数上使用,因为我准备好了'this.resJsonResponse'。你应该在你准备好Json响应之后调用它。 –
可以使用DomSanitizer预期
constructor(private sanitizer: DomSanitizer){}
generateDownloadJsonUri() {
var theJSON = JSON.stringify(this.resJsonResponse);
var uri = this.sanitizer.bypassSecurityTrustUrl("data:text/json;charset=UTF-8," + encodeURIComponent(theJSON));
this.downloadJsonHref = uri;
}
:需要 https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html
import语句:
import {enter code here DomSanitizer, SafeResourceUrl, SafeUrl} from '@angular/platform-browser';
constructor(private sanitizer: DomSanitizer){}
generateDownloadJsonUri() {
var theJSON = JSON.stringify(this.resJsonResponse);
var uri = this.sanitizer.bypassSecurityTrustUrl("data:text/json;charset=UTF-8," + encodeURIComponent(theJSON));
this.downloadJsonHref = uri;
}
请编辑您的答案以包含一些解释。仅有代码的答案对未来SO读者的教育很少。您的回答是在低质量的审核队列中。 – mickmackusa
当我的json非常大时,我遇到了一些问题,我在Ankur Akvaliya答案中添加了一个Blob对象,并且它可行!
generateDownloadJsonUri() {
let theJSON = JSON.stringify(this.resJsonResponse);
let blob = new Blob([theJSON], { type: 'text/json' });
let url= window.URL.createObjectURL(blob);
let uri:SafeUrl = this.sanitizer.bypassSecurityTrustUrl(url);
this.downloadJsonHref = uri;
}
创建数据URL,并将其分配给''https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs。您可以查找解释它的任何JavaScript答案,这在Angular中是一样的。 –