【发布时间】:2019-07-17 16:03:50
【问题描述】:
我正在使用HttpClient 从服务器读取 JSON 的内容。我可以成功读取一次内容,但是当我第二次读取时,它总是返回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 在我第一次读取 JSON 时正确导入到 app.module.ts,它可以正常工作。
这里是stackBlitz 的问题。
我正在使用setInterval,因为我希望能够在值更新时继续读取 JSON。我是否打算关闭 httpClient.get 请求,以便我可以再做一个。
我看到其他问题,请求总是返回 undefined,但我的只在第二次请求时和之后返回 undefined。
每次发送get请求如何成功获取JSON的内容?
【问题讨论】:
-
@Dino 不是重复的,因为
setinterval正在正确触发。请在标记之前查看链接的 StackBlitz。 -
您的 stackblitz 工作正常,是的,这是重复的。您得到的答案与我引用的那篇文章中的答案相同。请再检查一遍
标签: json angular angular-httpclient