Angular 4:如何使用HTTPClient读取文本文件的内容 [英] Angular 4: How to read content of text file with HTTPClient

查看:217
本文介绍了Angular 4:如何使用HTTPClient读取文本文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a .txt file in my Angular 4 project directory and I want to read its content. How to do it ? Below is the code which I employed.

该文件位于"app"文件夹中的"files"文件夹中. 我有HTTPClient代码的组件位于"app"文件夹中的"httpclient"文件夹中.

The file is in 'files' folder which is inside the 'app' folder. The component where i have HTTPClient code is in 'httpclient' folder which is inside 'app' folder.

含义为'files'文件夹和'httpclient'文件夹为子文件夹.

Meaning 'files' folder and 'httpclient' folder are children.

代码如下所示.它无法即时获得404错误-'GET http://localhost:4200/files/1.txt 404(未找到)"

The code is shown below. It not working as i m getting 404 error - 'GET http://localhost:4200/files/1.txt 404 (Not Found)'

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无法访问项目的应用程序目录内的文档.如果移至文本文档,则可以访问assets/1.txt之类的文本文件.

The CLI can't access docments inside the app directory your project. if you move to text document you can access the text file like assets/1.txt.

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

if you want to access document inside the app directory you need to add path in assets array in the .angular-cli.json

.angular-cli.json

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

以下是我的示例,请按以下方式尝试:

here below is my example try like this :

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

这篇关于Angular 4:如何使用HTTPClient读取文本文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆