Niko
Niko

Reputation: 1

Refresh text file contents to div in angular

I have a text file on the server which contents I would like to display in a div using angular updating on every second. How could I do that?

<div>Update text file here every second</div>

This is my code, something like this? Doesn't seem to work

<!DOCTYPE html>
<html>
<body>
<script>

private http: HttpClient;

 let myText: string;

  setInterval(() => { 
      getText();
  }
  ,1000);

  getText() {
    this.http.get("https://my.text.file/textFile.txt", { responseType: "text" }).subscribe(data => {
          this.myText = data;
    });
  }
	document.getElementById("text").innerHTML =
 this.myText(); 
	
	</script>

<div id="text"></div>


<script src="//code.angularjs.org/1.2.20/angular.js"></script>

</body>
</html>

Upvotes: 0

Views: 948

Answers (1)

JoH
JoH

Reputation: 554

The setInterval() allows to call a function at specified intervals.

  let myText: string;

  setInterval(() => { 
      getText();
  }
  ,1000);

  getText() {
     this.http.get("http://api.example.com/text_file", { responseType: "text" }).subscribe(data => {
          this.myText = data;
    });
  }

Inject the HttpClient into your component by adding private http: HttpClient in the constructor (it can be public or private).
Then add a new method, that we can call getText().
In that method, we call the HttpClient's post method.
Two important things at that point to note: the first parameter is the URL where the text file is stored or to access to it.
The second parameter is an object to set some options: here, we say to the HttpClient that the server will serve text instead of JSON (responseType: 'text').
Because HttpClient's get(), post(), delete() and put() methods return an Observable, we have to subscribe to it: so, to that subscribe() method, we pass a function (data => {}) to get our data.
That data have to be stored somewhere, so, earlier, we created a variable called myText that is a string variable.
We use that variable to store our data that can be shown in the component's view.

Angular team provided a tutorial to learn Angular principles, a good place to start.

Upvotes: 1

Related Questions