javascript - Angular 4 : How to read content of text file with HTTPClient

标签 javascript angular

我的 Angular 4 项目目录中有一个 .txt 文件,我想阅读它的内容。怎么做 ?下面是我使用的代码。

该文件位于“app”文件夹内的“files”文件夹中。 我拥有 HTTPClient 代码的组件位于“app”文件夹内的“httpclient”文件夹中。

意思是“files”文件夹和“httpclient”文件夹是子文件夹。

代码如下所示。它不工作,因为我收到 404 错误 - 'GET http://localhost:4200/files/1.txt 404(未找到)'

this.http.get('/files/1.txt').subscribe(data => {
        console.log(data);
    },
        (err: HttpErrorResponse) => {
            if (err.error instanceof Error) {
                // A client-side or network error occurred. Handle it accordingly.
                console.log('An error occurred:', err.error.message);
            } else {
                // The backend returned an unsuccessful response code.
                // The response body may contain clues as to what went wrong,
                console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
            }
        }
    );

最佳答案

像这样尝试:

this.http.get('app/files/1.txt').subscribe(data => {
    console.log(data.text());
})

CLI 无法访问您项目的 app 目录中的文档。如果你移动到文本文档,你可以访问像 assets/1.txt 这样的文本文件。

如果你想访问应用程序目录中的文档,你需要在 .angular-cli.json

的 Assets 数组中添加路径

.angular-cli.json

"assets": [
  "assets",
  "app", /* add this line to access document inside the app directory */
  "favicon.ico"
]

下面是我的示例,尝试这样:

this.http.get('app/home/1.txt').subscribe(data => {
    console.log('data', data.text());
})

关于javascript - Angular 4 : How to read content of text file with HTTPClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47053328/

相关文章:

javascript - Firebase Firestore Web v9 初始化

angular - 在查询参数更改时重新解析数据?

Angular2 全局变量可观察

javascript - Ionic 2 Tabs 超出最大调用堆栈大小

javascript - Angular UI Router 新 View ,相同的 URL

javascript - 通过 "MATCH (n) DETACH DELETE n"运行 "neo4j-driver"不起作用

javascript - 将重复出现的 JSON 名称转换为对象?

javascript - 如何从中心开始设置 div 的动画

javascript - 行高相对不变(基于其父div的大小)

angular - firebase.messaging 不是 Angular 9 中的函数