2017-10-11 280 views
1

我試圖在文件中保存json web響應。我可以創建並保存文件,但無法獲取網絡響應數據。在該文件中有隻有這個:[object Object]如何將文件保存爲文件?

這是我的組件:

import { Component, OnInit } from '@angular/core'; 
import { HttpClient } from '@angular/common/http'; 

@Component({ 
moduleId: module.id, 
templateUrl: 'home.component.html', 
styleUrls: ['home.component.css'] 
}) 

export class HomeComponent implements OnInit { 


constructor(private http: HttpClient) { 

} 

nodes: any; 
ngOnInit(): void { 
    // Make the HTTP request: 
    this.http.get('http://someUrl').subscribe(data => { 
    // Read the result field from the JSON response. 
    this.nodes = data; 
    this.downloadFile(this.nodes); 

    }); 

} 

downloadFile(data){ 
    let blob = new Blob([data], { type: 'text/plain;charset=utf-8;' }); 
    let dwldLink = document.createElement("a"); 
    let url = URL.createObjectURL(blob); 
    let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1; 
    if (isSafariBrowser) { //if Safari open in new window to save file with random filename. 
    dwldLink.setAttribute("target", "_blank"); 
    } 
    dwldLink.setAttribute("href", url); 
    dwldLink.setAttribute("download", "TEST.txt"); 
    dwldLink.style.visibility = "hidden"; 
    document.body.appendChild(dwldLink); 
    dwldLink.click(); 
    document.body.removeChild(dwldLink); 
} 

} 

回答

2

是必要的對象轉化爲它的字符串表示。其中一種方法是通過JSON.stringify

let blob = new Blob([ JSON.stringify(data) ], { type: 'text/plain;charset=utf-8;' }); 

這是胡亂猜測,但我期待你的 data對象是一個 response。因此,您可能需要調用它 .json()檢索實際有效載荷:

this.http.get('http://someUrl').subscribe(data => { 
    // Read the result field from the JSON response. 
    this.nodes = data; 
    this.downloadFile(this.nodes); 
}); 

由於您使用的一些HttpClient而不是標準Http服務的,​​這是很難說。您顯示的文件下載代碼與我在一個of my projects中工作的代碼匹配。

調試提示是否可以在您的瀏覽器控制檯上放置一個斷點 this.nodes = data.json();並執行 JSON.stringify(data)?然後用輸出更新你的問題。這將有助於理解你對 實際上是什麼對象處理。

+0

我試過了,但是我得到了這個錯誤:屬性'json'在'Object'類型上不存在。 – eli

+0

它現在工作,謝謝,你可能想編輯你的答案 – eli

+0

@eli更新了答案 –