typescript - 如何從 Angular 應用程式讀取和寫入本地文件
我正在建構一個 Angular 7 的網頁應用程式,並且我想加入讓使用者完成問卷並提交結果的功能。在我能設置資料庫來儲存資訊之前,我想將結果存儲在本地的 json 檔案中。然而,我在尋找一種方式將資料附加到現有的本地檔案時遇到困難,而不使用 Node.js 的 'fs' 模組(我讀到這個功能在 Angular 6-7 中無法使用)。
難道我沒有辦法做到這件事嗎?我知道這不是最好的方法,我計劃在應用程式運行起來之後,加入伺服器端和資料庫功能。
答案#1
你可以使用 fileSaver。
嘗試以下內容
npm install file-saver --save
然後在你的專案中添加一個宣告文件,如 'declarations.d.ts',並在其中放置
declare module 'file-saver';
在你的 systemjs.config.js 中,將以下內容添加到 map 部分
'file-saver': 'npm:file-saver/FileSaver.js'
然後像下面這樣在你的組件或服務中導入該函式庫
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')
}
}
希望有幫助。
答案#2
Angular 只適用於客戶端。你無法將檔案保存到伺服器端
