HttpClient returns json 一次然后 returns undefined

HttpClient returns json once and then returns undefined

我正在使用 HttpClient 从服务器读取 JSON 的内容。我能够成功阅读一次内容,但是当我第二次阅读时,它总是 returns 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)
   }
}

HttpClient 被正确导入 app.module.ts,因为我第一次阅读 JSON 它没有问题。

这是一个 stackBlitz 问题。

我正在使用 setInterval,因为我希望能够在值更新时继续阅读 JSON。我是不是要关闭 httpClient.get 请求以便我可以再做一个。

我看到其他问题,请求总是 returns undefined 但我的请求只有 returns undefined 在第二次请求时和之后。

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

编辑 显然对于某些人来说,我的 stackblitz 工作不是问题,这里是控制台 stackblitz 的屏幕截图:

this 在调用 setInterval 的函数中没有指向 class。

改用箭头函数。

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

你用过this.getData,应该是this.getData() 而且你必须使用箭头函数。

试试这个:

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

使用箭头函数是一个很好的回应,但使用时要小心setInterval。 您绝对应该更喜欢在 Angular 应用程序上下文中使用 RxJS:

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

setInterval 的不良做法用法:https://dev.to/akanksha_9560/why-not-to-use-setinterval--2na9