Angular 4:如何使用HTTPClient读取文本文件的内容

yog*_*ing 11 javascript angular

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

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

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

代码如下所示.它没有工作因为我得到404错误 - '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}`);
            }
        }
    );
Run Code Online (Sandbox Code Playgroud)

Cha*_*dru 21

试试这样:

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

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

如果要访问app目录中的文档,则需要在.angular-cli.json中的assets数组中添加路径

.angular-cli.json

"assets": [
  "assets",
  "app", /* add this line to access document inside the app directory */
  "favicon.ico"
]
Run Code Online (Sandbox Code Playgroud)

下面是我的例子尝试这样:

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

  • 你太棒了!我必须重新启动我的角度项目.我正在使用vs代码.所以我关闭它并重新打开它并再次运行应用程序.现在我能够评估它.这里的代码是this.http.get('app/files/1.txt',{responseType:'text'}) (2认同)

nsk*_*nsk 12

角度6/7

{responseType:'text'为'json'}

现在工作

this.http.get("app/files/1.txt",{responseType:'text'as'json'}).subscribe(data => {console.log(data.text());})

有关完整的讨论,请参阅https://github.com/angular/angular/issues/18586