0

Can someone point me in the right direction? I have a static json file stored in my assets directory that I import throughout a few components. However, I want to periodically fetch a json from a server and check for updates and then do some post-processing on the static version in my assets directory after the fetch (essentially make a copy with some modifications). What’s the best way to do this with Angular 7? I only want to fetch updates and do the post-processing once a day or maybe even once a week.

Currently, I import the static json like this:

import mlbPlayers from '../../assets/data/players-mlb.json';

Something like this but in the "Angular" way

Smooth
  • 956
  • 1
  • 15
  • 37

1 Answers1

0

Subscribe to fileData$ observable

const API_URL = './assets/data/db.json';
public fileData = new ReplaySubject<any>(1);
fileData$: Observable<any> = this.fileData.asObservable();

constructor(private http: HttpClient) { 
   this.getFileData();
}

//repeats every 5 seconds
getFileData(): void {
     Observable.interval(5000)
        .switchMap(() => this.http.get(API_URL).subscribe(res => {
       this.fileData.next(res);
     }));
}
Prasanth
  • 507
  • 2
  • 10
  • Will this work if it's a 1-week long interval or 24 hour? Won't the Observable interval reset on each initialization? – Smooth Apr 30 '19 at 17:02
  • It will work with angular only when you have a client always running. Yes, it will initialize for every user of your application. If there are 10 users, you will have 10 jobs for json files. Unless that's what you want, I would suggest take this logic to middleware and handle it if it matches a cron job – Prasanth Apr 30 '19 at 18:10
  • I dont mind if it runs for every user I'm just wondering if the interval will reset if the user closes the website and then comes back to it later – Smooth Apr 30 '19 at 18:51
  • It is a cron job depending on whether user exists in your app. It initializes for every refresh of the screen – Prasanth Apr 30 '19 at 18:57
  • so the first initialization will continue successfully even one week later even if the user navigates away from the page before the one-week interval is complete? – Smooth Apr 30 '19 at 19:41
  • Once you move away from website, it won't be triggered (because there is no server it is running on). All you need is a cron job functionality which can be easily implemented from middleware server – Prasanth May 01 '19 at 00:10
  • do you have an example you can link me to thats implemented with an angular app? its my first time doing something like this – Smooth May 01 '19 at 01:04