here i want to know how can i create a text file or json file and download it with dynamic data which is going to be filled with.
below is my
service code
validateUserData(userId) {
var headers = new Headers();
return this.http.get(`${this.baseUrl}/Users?userId=`+userId,{headers: headers}).map(result => {
return result.json();
});
}
component.ts
this.service.validateUserData(userId).subscribe( res => {
console.log(res);
new Angular2Txt(res, 'My Report');
});
here i want to send the Response to a textFile or json file which i have to create it so that user can able to download how can i do it Angular package
i tried the above package but i able to download only empty file
it does not have to use any package,try this
https://stackblitz.com/edit/httpsstackoverflowcomquestions51806464how-to-create-and-downloa?file=src/app/app.component.ts
@Component({
...
})
export class AppComponent {
private setting = {
element: {
dynamicDownload: null as HTMLElement
}
}
fakeValidateUserData() {
return of({
userDate1: 1,
userData2: 2
});
}
//
dynamicDownloadTxt() {
this.fakeValidateUserData().subscribe((res) => {
this.dyanmicDownloadByHtmlTag({
fileName: 'My Report',
text: JSON.stringify(res)
});
});
}
dynamicDownloadJson() {
this.fakeValidateUserData().subscribe((res) => {
this.dyanmicDownloadByHtmlTag({
fileName: 'My Report.json',
text: JSON.stringify(res)
});
});
}
private dyanmicDownloadByHtmlTag(arg: {
fileName: string,
text: string
}) {
if (!this.setting.element.dynamicDownload) {
this.setting.element.dynamicDownload = document.createElement('a');
}
const element = this.setting.element.dynamicDownload;
const fileType = arg.fileName.indexOf('.json') > -1 ? 'text/json' : 'text/plain';
element.setAttribute('href', `data:${fileType};charset=utf-8,${encodeURIComponent(arg.text)}`);
element.setAttribute('download', arg.fileName);
var event = new MouseEvent("click");
element.dispatchEvent(event);
}
}
<a (click)="dynamicDownloadTxt()" >download Txt</a>
<a (click)="dynamicDownloadJson()" >download JSON</a>
Firstly, there is a library we can use to handle saving the file. I've just tested it with FileSaver which seems to work, so that seems a good place to start.
Secondly, configure your HTTP request to return a Blob. Using HttpClient
, we can simply do:
let url = "https://jsonplaceholder.typicode.com/todos/1";
this.http.get(url, {responseType: 'blob'})
Finally, in the subscribe, save the blob. Using the npm
package I mentioned earlier, this would be done like so:
import { saveAs } from 'file-saver/FileSaver';
// ...
let url = "https://jsonplaceholder.typicode.com/todos/1";
this.http.get(url, {responseType: 'blob'})
.subscribe((res) => {
console.log(res)
saveAs(res, "myfile.json")
})
The second option is the filename.
Here is StackBlitz demo
Just uncomment the saveAs
line if you want to see it download the file.
You could do it like this:
let res = "Text to save in a text file";
const blob = new Blob([res], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
window.open(url);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With