JackU
JackU

Reputation: 1476

HttpClient returns json once and then returns undefined

I am reading the contents of a JSON from a server using HttpClient. I am able to read the contents once successfully but when I read it a second time it always returns undefined.

This is what my .ts looks like:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  constructor(private httpService: HttpClient) { }

  getData() {
    this.httpService.get('https://raw.githubusercontent.com/LearnWebCode/json-example/master/animals-1.json').subscribe(
          result => { 
            console.log(result)
          }
    )
  }

   ngOnInit() {
     this.getData()
     setInterval(this.getData, 10000)
   }
}

HttpClient is imported into app.module.ts correctly as the first time I read the JSON it works without a problem.

Here is a stackBlitz with the issue.

I am using setInterval because I want to be able to keep reading the JSON as the values will update. Am I meant to be closing the httpClient.get request so that I can make another.

I have seen other questions where the request always returns undefined but mine only returns undefined on and after the second request.

How do I successfully get the contents of the JSON each time I send the get request?

EDIT Apparently for some my stackblitz works not a problem, here is a screenshot from the stackblitz of the console with the issue:
enter image description here

Upvotes: 2

Views: 226

Answers (3)

Martin Choraine
Martin Choraine

Reputation: 2431

Use of arrow function is a great response but you should be careful when using setInterval. You should definitely prefer usage of RxJS in an Angular application context :

interval(10000).pipe(
   mergeMap(() => this.getData())
).subscribe()

Bad practices usage of setInterval : https://dev.to/akanksha_9560/why-not-to-use-setinterval--2na9

Upvotes: 0

Adrita Sharma
Adrita Sharma

Reputation: 22213

You have used this.getData, it should be this.getData() and you have to use an arrow function.

Try this:

setInterval(() => this.getData(), 10000);

Upvotes: 1

pajtim
pajtim

Reputation: 567

this in the function given to setInterval doesn't point to the class when it is called.

Use arrow function instead.

    setInterval(() => { this.getData(); }, 10000);

Upvotes: 5

Related Questions