2017-10-11 228 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更新了答案 –