I am trying to open a .txt file which is in my assets folder. The name is "Maze1.txt". I am sort of new to these things so I was wondering if someone can help me read the text from this file. Thank you so much. If there is any more information needed, please tell me. :)
Angular: How do I read a text file located in the assets folder?
You can use the HttpClient for this (import and inject it as httpClient
).
this.httpClient.get('assets/Maze1.txt', {responseType: 'text'})
.subscribe(data => console.log(data));
I tried that, but I keep getting this error even after declaring http: Cannot read property 'get' of undefined –
Intone
has you import the HttpClientModule from '@angular/common/http' in your module and HttpClient in your service/component from '@angular/common/http'. ? see the doc: angular.io/guide/http –
Yvetteyvon
This is what I added in my app module: import { HttpClientModule } from '@angular/common/http'; and I also put it in the imports array. For my component, I added this on top: import { HttpClient } from '@angular/common/http'; It still does not work –
Intone
I also added import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators'; –
Intone
Nevermind. I found a working solution by using a constructor. For anyone looking for code that works, use this:
private httpClient: HttpClient;
constructor(http: HttpClient) {
this.httpClient = http;
}
and in the function: I used this:
this.httpClient.get('assets/Maze1.txt', { responseType: 'text' })
.subscribe(data => console.log(data));
Timon answer implied you injected HttpClient in the constructor, so might be better to just ask him to edit his answer. Also, a better way to inject HttpClient would be to delete the httpClient variable you declared, that is delete the line
private httpClient: HttpClient;
and change the constructor to constructor(private httpClient: HttpClient) {}
. –
Doodle I got this error by having a wrong import:
I had this
import { HttpClient } from '@microsoft/signalr';
instead of
import { HttpClient } from '@angular/common/http';
© 2022 - 2025 — McMap. All rights reserved.