HttpClient返回一次json,然后返回undefined

Jac*_*ckU 2 json angular angular-httpclient

我正在使用从服务器读取JSON的内容HttpClient。我能够成功读取一次内容,但是当我第二次读取它时,它总是返回undefined

这是我的.ts样子:

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)
   }
}
Run Code Online (Sandbox Code Playgroud)

HttpClientapp.module.ts在我第一次阅读JSON时已正确导入,它可以正常工作。

这是有问题的stackBlitz

我正在使用,setInterval因为我希望能够继续读取JSON,因为值将更新。我是否打算关闭httpClient.get请求,以便我可以提出另一个请求。

我看到了其他问题,其中请求始终返回,undefined而我的请求仅undefined在第二个请求之后返回。

每次发送get请求时,如何成功获取JSON的内容?

编辑 显然,对于我的某些stackblitz来说,这不是问题,这是来自控制台的stackblitz的屏幕截图,其中包含以下问题:
在此处输入图片说明

paj*_*tim 5

在给setInterval的函数被调用时不指向类。

请改用箭头功能。

    setInterval(() => { this.getData(); }, 10000);
Run Code Online (Sandbox Code Playgroud)