在Angular4应用程序中读取非静态JSON文件

在Angular4应用程序中读取非静态JSON文件,json,angular,Json,Angular,我有一个基本的Angular web应用程序,它读取与应用程序位于同一服务器上的JSON文件,并通过JSON文件进行解析,以便在驱动我的应用程序中的某些行为的对象上设置某些值(应用css类等) 我无法在线找到和/或自己弄清楚如何设置控制器,以便从JSON文件中读取文件,从而允许更改文件,并在更改后动态重新加载文件,而无需重新加载整个页面。JSON文件在部署应用程序的服务器上是本地的,我希望避免仅仅为了服务已经存在于部署应用程序的同一服务器上的文件而建立web服务 以下是我现在正在做的事情: ng

我有一个基本的Angular web应用程序,它读取与应用程序位于同一服务器上的JSON文件,并通过JSON文件进行解析,以便在驱动我的应用程序中的某些行为的对象上设置某些值(应用css类等)

我无法在线找到和/或自己弄清楚如何设置控制器,以便从JSON文件中读取文件,从而允许更改文件,并在更改后动态重新加载文件,而无需重新加载整个页面。JSON文件在部署应用程序的服务器上是本地的,我希望避免仅仅为了服务已经存在于部署应用程序的同一服务器上的文件而建立web服务

以下是我现在正在做的事情:

ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('../assets/applicationLogs.json').subscribe(data => {
        // Read the result field from the JSON response.
        this.node_a_status= data.nodes[0].status;
        this.node_b_status= data.nodes[1].status;
        this.node_c_status= data.nodes[2].status;
    }); 
}
下面是我的JSON文件的外观:

{
    "nodes":[
        { "node":"Node A", "status":"processing", "errors":null },
        { "node":"Node B", "status":"processing", "errors":null },
        { "node":"Node C", "status":"inactive", "errors":null }
        ]
}

首先,我知道我可能需要将这个get逻辑移出
ngOnInit()
,但我对如何实现我用typescript描述的所需行为有点迷茫。

您正在对文件使用http请求方法,所以“轮询它”。。。与任何其他http JSON服务的方式相同。这里有一个现成的轮询器供您导入:

您所能做的最好的事情就是用它创建一个服务,并用ngOnInit方法调用它,然后以您所展示的相同方式使用响应

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/dom/ajax';
import 'rxjs/add/operator/map';

import polling from 'rx-polling';

// Example of an Observable which requests some JSON data
const request$ = Observable.ajax({
    url: '../assets/applicationLogs.json',
    crossDomain: true
  }).map(response => response.response || [])
  .map(response => response.slice(0, 10)); // Take only first 10 comments

polling(request$, { interval: 5000 }).subscribe((comments) => {
  console.log(comments);
}, (error) => {
  // The Observable will throw if it's not able to recover after N attempts
  // By default it will attempts 9 times with exponential delay between each other.
  console.error(error);
});