Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

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

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.

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.

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

The code is shown below. It not working as i m getting 404 error - '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}`);
            }
        }
    );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...