我的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}`);
}
}
);
答案 0 :(得分:14)
试试这样:
this.http.get('app/files/1.txt').subscribe(data => {
console.log(data.text());
})
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"
]
下面是我的示例尝试这样:
this.http.get('app/home/1.txt').subscribe(data => {
console.log('data', data.text());
})
答案 1 :(得分:10)
角度6/7
{responseType:'text'as'json'}
目前有效
this.http.get(“ app / files / 1.txt”,{responseType:'text'as'json'})。subscribe(data => { console.log(data.text()); })
答案 2 :(得分:3)
只需对前一个答案进行一次更正: 添加&#34; responseType:&#39; text&#39;&#34;选项:
this.http.get("app/files/1.txt", "{ responseType: 'text' }").subscribe(data => {
console.log(data.text());
})
答案 3 :(得分:1)
我能够通过 Angular 6 项目获得本地文件(JSON)。
项目结构:
|-src
|--app
|---core
|---...
|---app.module.ts
|--assets
|...
步骤:
1)在angular.json
内,我添加了放置文件的文件夹:
"projects": {
"my-project": {
"root": "",
"sourceRoot": "src", // ** my project root is "src" folder
"projectType": "application",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
// ...
"assets": [
"src", // <--- ADDED THIS
"src/assets",
"src/favicon.ico",
"src/manifest.json",
"src/robots.txt",
"src/web.config"
]
2)编写了以下服务以获取文件:
import { HttpClient } from '@angular/common/http'
import { Injectable } from '@angular/core'
@Injectable({
providedIn: 'root'
})
export class EnvironmentService {
constructor(private readonly _httpClient: HttpClient) {
}
public init(): Promise<any> {
return new Promise(resolve =>
this._httpClient
.get('file.json')
.first()
.subscribe((data: any) => {
// data from JSON
resolve()
})
)
}
}
奖金:
如果要读取自定义环境变量(标准Angular提供的变量除外),可以将上述服务添加到App.module.ts
中:
export function init_app(appLoadService: EnvironmentService): () => Promise<any> {
return () => appLoadService.init()
}
@NgModule({
// ...
providers: [
EnvironmentService,
{ provide: APP_INITIALIZER, useFactory: init_app, deps: [ EnvironmentService ], multi: true },
],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
P.S。如果出现问题,您可以检查this one。
答案 4 :(得分:1)
这已在Angular 6
使用
创建服务import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
//Read text file
export interface ResultJson{
}
@Injectable({
providedIn: 'root'
})
export class TestService {
urlEncoded = '/Test.text';
getText(){
return this.http.get(this.urlEncoded, {responseType: 'text'});
}
}
并按如下所示调用组件中的服务
resultJSON: ResultJson;
ResultJsonString : any;
this
.testService
.getText()
.subscribe((data:ResultJson) => {
this.ResultJsonString = data;
});
希望这对您有帮助