Angular: How do I read a text file located in the assets folder?
Asked Answered
I

3

5

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. :)

Intone answered 22/6, 2020 at 21:17 Comment(0)
N
13

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));
Nordin answered 22/6, 2020 at 21:29 Comment(4)
I tried that, but I keep getting this error even after declaring http: Cannot read property 'get' of undefinedIntone
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/httpYvetteyvon
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 workIntone
I also added import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators';Intone
I
5

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));
Intone answered 23/6, 2020 at 3:14 Comment(1)
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
R
0

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';
Robichaud answered 10/8, 2024 at 4:28 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.