我的 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/