I am quite new to Angular. In my project, I load different local .json files using http-requests. It works but I am asking myself, if there is a more elegant solution.
I load the local files like this:
// load data from file1
this.http.get("./assets/file1.json").subscribe(data => {
this.file1 = data
})
// load data from file2
this.http.get("./assets/file2.json").subscribe(data => {
this.file2 = data
})
... (repeat for every single file)
I need the data from every file to be stored in a separate variable (called this.file1, this.file2, ... in my example). These http requests I call in the ngOnInit()
.
I have already tried to do something using Observables, calling a function and subscribing to the data, but I do not know how to combine that for my different files.
this.loadFiles().subscribe(data => {
this.file1 = data
});
public loadFiles(): Observable<any> {
return this.http.get("./assets/file1.json");
}
I would be highly interested to see, how nice code for this task would look like.
Have an array of filenames, map the file names to an array of http requests. forkJoin will fire them all at once and when they have all completed the array of results will be returned in the same order as the original array.
const files = ['file1', 'file2', 'file3'];
forkJoin(files.map(file => this.http.get(`./assets/${file}.json`))).subscribe(files => {
// do stuff with files
});