简体   繁体   中英

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. Right now I am using http.get to call a local json file and render the data on initial load. 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. 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.

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. 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.

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

The above code will allow you to import your json file in your component.

Now go to your component and import your json file. For example:

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

Next, you can use this little hack to get the contents of the json file.

cities: any = cities

Now in your view, you can reference it in let's say an 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. Add typings.d.ts file in your project root with:

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

Then you can use it in your code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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