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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47053328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:42:57  来源:igfitidea点击:

Angular 4: How to read content of text file with HTTPClient

javascriptangular

提问by yogihosting

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.

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

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.

该文件位于“app”文件夹内的“files”文件夹中。我拥有 HTTPClient 代码的组件位于“app”文件夹内的“httpclient”文件夹中。

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

意思是 'files' 文件夹和 'httpclient' 文件夹是子文件夹。

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

代码如下所示。它不起作用,因为我收到 404 错误 - 'GET http://localhost:4200/files/1.txt404 (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}`);
            }
        }
    );

回答by Chandru

Try like this :

像这样尝试:

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

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.

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

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中的资产数组中添加路径

.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());
})

回答by nsk

Angular 6/7

角 6/7

{ responseType: 'text' as 'json'}

{ responseType: 'text' 为 'json'}

for now works

现在工作

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

Refer to this ticketon GitHub for the complete discussion.

有关完整讨论,请参阅GitHub 上的此票证

回答by Doron Saar

Just one correction to the previous answer: add "responseType: 'text'" to the options:

只是对上一个答案的一个更正:将“responseType:'text'”添加到选项中:

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

回答by Arsen Khachaturyan

I was able to get a local file(JSON) with Angular 6project.

我能够使用Angular 6项目获取本地文件(JSON)。

Project strucuture:

项目结构:

|-src
|--app
|---core
|---...
|---app.module.ts
|--assets
|...

Steps:

脚步:

1) Inside angular.jsonI've added the folder where I put the file:

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) Wrote following service to get the file:

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()
         })
      )
   }
}

Bonus:
In case if you want to read custom environment variables(besides what standard Angular one provides) you can add above service into App.module.ts:

奖励
如果您想读取自定义环境变量(除了标准的 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. In case of issues you can check this one.

PS 如果出现问题,您可以检查这个

回答by user2112373

This is tested in Angular 6

这是在测试 Angular 6

Create a service using

使用创建服务

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'});
  }
}

and call the service in your component like below

并在您的组件中调用服务,如下所示

  resultJSON: ResultJson;
  ResultJsonString : any;
this
    .testService
    .getText()
    .subscribe((data:ResultJson) => {
         this.ResultJsonString = data;
       });

Hopefully this helps

希望这会有所帮助