Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Angular2导出/下载json文件_Javascript_Json_Angular_Download_Export - Fatal编程技术网

Javascript Angular2导出/下载json文件

Javascript Angular2导出/下载json文件,javascript,json,angular,download,export,Javascript,Json,Angular,Download,Export,我用的是angular 2。我想提供下载JSON文件的功能 就像我有res={bar:foo}的响应一样,然后我想创建一个json文件,它将包含这个响应,可以在单击按钮/锚点时下载 任何帮助都将不胜感激 这比预期的要简单 constructor(private sanitizer: DomSanitizer){} generateDownloadJsonUri() { var theJSON = JSON.stringify(this.resJsonResponse);

我用的是angular 2。我想提供下载JSON文件的功能

就像我有res={bar:foo}的响应一样,然后我想创建一个json文件,它将包含这个响应,可以在单击按钮/锚点时下载


任何帮助都将不胜感激

这比预期的要简单

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;
    }
在模板中包括

<a class="btn btn-clear" title="Download JSON" [href]="downloadJsonHref" download="download.json"></a>

您可以使用DOMSanizer:

需要导入语句:

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;
}

当我的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;
}

纯JavaScript将完成这项工作

downloadJson(myJson){
    var sJson = JSON.stringify(myJson);
    var element = document.createElement('a');
    element.setAttribute('href', "data:text/json;charset=UTF-8," + encodeURIComponent(sJson));
    element.setAttribute('download', "primer-server-task.json");
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click(); // simulate click
    document.body.removeChild(element);
}

创建数据URL并将其分配给
。您只需查找任何解释它的JavaScript答案,角度相同。请编辑您的答案以包含一些解释。只有代码的答案对教育未来的读者几乎没有什么作用。您的答案因质量低而在审核队列中。如何或何时生成WnloadJSONURI()调用我已在构造函数上使用,因为我已准备好了此.resJsonResponse。您应该在Json响应就绪后调用它。它为我下载html文件,而不是Json数据。您可能应该尝试使用Blob。我没有将下载属性添加到,并且正在努力找出它不起作用的原因。这是必需的!