2017-02-21 5 views
5

私は角度2を使用しています。私はJSONファイルをダウンロードする機能を与えたいと思います。jsonファイルをエクスポート/ダウンロードするAngular2

私はres = {bar:foo}のレスポンスを持っていますので、ボタン/アンカークリックでダウンロードできるこのレスポンスを含むjsonファイルを作成します。

ご協力いただきますようお願い申し上げます。

答えて

8

私はあなたがDomSanitizerを使用することができますテンプレート

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

いつ、どのようにgenerateDownloadJsonUri()が呼び出されました –

+1

私は 'this.resJsonResponse'を準備していたのでコンストラクタで使用しました。 Json Responseの準備ができたら、それを呼び出す必要があります。 –

0

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 {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; 
} 
+0

解説を編集して説明を加えてください。コードのみの回答は、今後のSO読者の教育にはほとんど役に立ちません。あなたの答えは低品質であるためにモデレーションキューにあります。 – mickmackusa

1

私の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; 
} 
関連する問題