简体   繁体   English

如何从角度应用程序读取和写入本地文件

[英]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. 我正在构建Angular 7网络应用程序,并且正在尝试合并一些功能,以便用户完成调查并提交结果。 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. 在我能够建立一个数据库来存储信息之前,我想将结果存储在本地json文件中。 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). 但是,我很难找到一种无需使用Node.js'fs'模块即可附加到现有本地文件的方法(我已阅读到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. 您可以使用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 然后向您的项目中添加一个声明文件,例如“ declarations.d.ts”,并放入其中

declare module 'file-saver';

In your systemjs.config.js, add the following to the map section 在您的systemjs.config.js中,将以下内容添加到map部分

'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. 我一直在研究解决方案,但我不认为有办法实现我想做的事情,我认为这部分是由于Angular的设计方式所致。 I have decided to just bite the bullet now instead of later and am incorporating Firebase into my app. 我决定现在就硬着头皮,而不是稍后再将Firebase整合到我的应用程序中。 From what I have read, it is relatively quick and does not require much effort on my part 根据我的阅读,它相对较快,不需要我付出很多努力

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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