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更新了答案 –