Angular4 - 如何实时刷新来自网络服务的数据?

Angular4 - How do I refresh data from web-service in real time?

我正在从 Web 服务获取 JSON 数据。我目前有一个实时显示这些数据的网页,但除非我按 F5 手动刷新页面,否则不会显示新值。如何监听新响应并将最近的数据实时显示到 Html?如果有任何不清楚的地方,请告诉我。

谢谢

组件

 ngOnInit(): void {
IntervalObservable.create(1000)
  .subscribe(() => {
    this.appService.getDataLN().subscribe(resLN => {
      //
      ];
      names.forEach(name => {
        this.findLastValueLN(resLN, name);
      })
    }, error => console.log(error))


    this.appService.getDataLS().subscribe(resLS => {
      let names = [
       //
      ];
      names.forEach(name => {
        this.findLastValueLS(resLS, name);
      })
    }, error => console.log(error)
    )}


  findLastValueLN(resLN, name: String) {
let index = resLN.Object.Table.findIndex(d => 
d.objectName[d.objectName.findIndex(objectName => objectName === name)]);
if (resLN.Object.Table[index].objectName == "status") {
  if (resLN.Object.Table[index].LastValue == "on") {
    let index_A = resLN.Object.Table.findIndex(actual => 

html

<div>{{this.arrLN_[0]</div>
//expected arrLN_[2] to be printed only when status is off.. 
<div>{{this.arrLN_[2]</div> 

这是您要找的东西吗?

ngOnInit(){
    IntervalObservable.create(1000)
        .subscribe(() => {
            this.appService.getDataLN().subscribe(res => {
                let names = [//some name fileds that I need to serach from JSON];
                names.forEach(name => {
                    this.findLastValueLN(res, name);
                })
            }, error => console.log(error););
            this.appService.getDataLK().subscribe(res => {
                let names = [//some name fileds that I need to serach from JSON];
                names.forEach(name => {
                    this.findLastValueLN(res, name);
                })
            }, error => console.log(error););
        }
      });
}

这将基本上每秒轮询一次您的后端并更新结果。 :)

可能还想查看 .takeWhile 可观察修饰符,以确保代码 运行 仅当该组件处于活动状态时。

您可以在您的组件中声明一个变量:

result = Observable<any>;

然后以这种方式调用服务:

this.result = myservice.getDataLN();

在您的 html 文件中,您可以使用异步管道始终显示新值而无需在 component.ts 中订阅,因此您将在 html 文件中拥有此内容:

{{result | async }}