简体   繁体   中英

How to read and write from angular app to local file

I am building an Angular 7 web app and I am trying to incorporate functionality for users to complete a survey and submit the results. Until I am able to set up a database to store the info, I was wanting to store the results in a local json file. However, I am having trouble finding a way to append to an existing local file without using Node.js 'fs' module (I have read that this functionality cant be used with Angular 6-7).

Is there no way for me to do this? I know it is not the best way and I plan on incorporating server side and database functionality after I get the app up and running.

You can make use of fileSaver.

Try the following

npm install file-saver --save

Then add a declarations file to your project like 'declarations.d.ts' and in it put

declare module 'file-saver';

In your systemjs.config.js, add the following to the map section

'file-saver': 'npm:file-saver/FileSaver.js'

And then import the library in your component or service like below

import { Component } from '@angular/core';
import * as saveAs from 'file-saver';


@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
  <button (click)="SaveDemo()">Save File</button>`,
})
export class AppComponent {
  name = 'Angular';

  SaveDemo() {
    let file = new Blob(['hello world'], { type: 'text/csv;charset=utf-8' });
    saveAs(file, 'helloworld.csv')
  }
} 

Hope it helps.

I have kept looking into my solution but I do not believe there is way to achieve what I am trying to do, and I think it is in part due to how Angular is designed. I have decided to just bite the bullet now instead of later and am incorporating Firebase into my app. From what I have read, it is relatively quick and does not require much effort on my part

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM