【发布时间】:2018-04-13 16:19:41
【问题描述】:
我的 Angular 4 项目目录中有一个 .txt 文件,我想阅读它的内容。怎么做 ?下面是我使用的代码。
该文件位于“app”文件夹内的“files”文件夹中。 我拥有 HTTPClient 代码的组件位于“app”文件夹内的“httpclient”文件夹中。
意思是“文件”文件夹和“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}`);
}
}
);
【问题讨论】:
-
您尝试过相对 URL 吗? (即
http.get('files/1.txt')-- 没有初始斜线)或者将文件放在assets文件夹中,我相信它的内容会被复制到站点的根目录中。 -
是的,我刚才试过了,同样的错误。它没有找到它 - 404。怎么了?我只是遵循官方 Angular 文档angular.io/guide/http#requesting-non-json-data 的代码
-
你的文件路径正确吗?
-
是的,文件路径是正确的。即使我将文本文件移动到组件的同一文件夹并执行 this.http.get('./1.txt') 我也会收到相同的错误。
-
@yogihosting 它不起作用,因为当 CLI 使用
ng serve构建项目时,它只处理 .ts、.html 和 .css 文件。 .txt 文件等静态资源不属于您的代码,它们会被ng serve删除。
标签: javascript angular