简体   繁体   English

从本地json文件Http初始加载数据,然后通过另一个调用刷新不同角度的文件的数据4

[英]Http initial load data from local json file, then refreshing data via another call to a different file angular 4

I am working on an angular application with the angular cli. 我正在使用角度cli进行角度应用。 Right now I am using http.get to call a local json file and render the data on initial load. 现在,我正在使用http.get调用本地json文件,并在初始加载时呈现数据。 My task is after a certain amount of time of initial load, I am supposed to call data from a different local json file and update the UI to reflect the new data. 我的任务是经过一定时间的初始加载后,我应该从其他本地json文件中调用数据并更新UI以反映新数据。 I am unsure of the best way to approach this. 我不确定解决此问题的最佳方法。 Can someone provide some examples of a data refresh? 有人可以提供一些数据刷新示例吗?

You can use the setTimeout function. 您可以使用setTimeout函数。

eg 例如

setTimeout(() => {
   // Load from the other json file
}, 1000);

Let's say, you want to use a json file that contains a list of cities and you want to reference the city names in a dropdown list, this is how you will go about it. 假设您要使用一个包含城市列表的json文件,并且要在下拉列表中引用城市名称,这就是您要使用的方式。 Since you are using the Angular Cli, that means you are using Webpack so first of all, go to typings.d.ts and insert an object like this. 由于您使用的是Angular Cli,这意味着您使用的是Webpack,因此,首先,请转到typings.d.ts并插入一个这样的对象。

declare module "*.json" {
  const value: any;
  export default value;
}

The above code will allow you to import your json file in your component. 上面的代码将允许您在组件中导入json文件。

Now go to your component and import your json file. 现在转到您的组件并导入json文件。 For example: 例如:

import * as cities from "./cities.json"

Next, you can use this little hack to get the contents of the json file. 接下来,您可以使用这个小技巧来获取json文件的内容。

cities: any = cities

Now in your view, you can reference it in let's say an ngFor 现在,您认为可以在ngFor引用它

 <select>
   <option *ngFor='let city of cities'>{{city.name}}</option>
 </select>

Try something like this: 尝试这样的事情:

file1$ = this.http.get('file1.json');
file2$ = this.http.get('file2.json').delay(1000);


Observable.combineLatest(file1$, file2$)
  .subscribe(([file1, file2]) => { ... })

If your json files are only local you can also import them directly. 如果您的json文件仅是本地文件,则也可以直接导入它们。 Add typings.d.ts file in your project root with: 使用typings.d.ts命令在项目根目录中添加typings.d.ts文件:

declare module '*.json' {
  const value: any;
  export default value;
}

Then you can use it in your code: 然后可以在代码中使用它:

import * as file1 from './file1.json';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM