简体   繁体   中英

Angular 7 - Fetch json from server only periodically and store locally in Angular app

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

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);
     }));
}

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