As a newcomer to Angular, I've been working on a project where I need to load various local .json files using http-requests. While my current approach works, I can't help but wonder if there's a more elegant solution.
Currently, I load the local files in this manner:
// 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 each file)
Each file's data needs to be stored in a separate variable (like this.file1, this.file2, etc.), and these http requests are made in the ngOnInit()
method.
I've attempted using Observables, creating a function and subscribing to the data, but I'm unsure of how to apply it to multiple files.
this.loadFiles().subscribe(data => {
this.file1 = data
});
public loadFiles(): Observable<any> {
return this.http.get("./assets/file1.json");
}
I would greatly appreciate seeing some clean code examples for handling this task.