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);
}
}
我试过了,但是我得到了这个错误:属性'json'在'Object'类型上不存在。 – eli
它现在工作,谢谢,你可能想编辑你的答案 – eli
@eli更新了答案 –