I would like to specify a local path to a JSON file as an attribute in HTML, similar to the src
property of an HTML img
.
Ideally, something like this:
<my-component data-source="localPath">
where localPath
corresponds to the path of a local JSON file that contains the data that will be used to populate the my-component
. This way I can use the same component multiple times in my HTML, but just change which JSON file each instance reads from for populating data.
For a single instance, I know the following works (inside of my-component.component.ts
):
import myData from 'localPath';
let content = myData.data as MyInterface;
This is from an earlier question I posted about reading JSON files in Angular 12. The issue here, of course, being that all instances of my-component
would be stuck using the same JSON file located at localPath
.
I suspect that creating a service to "load" the file, much the same way you might read an external URL/API would work... but is there a simpler way? I am just trying to read a local file, not data from an external URL.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(public http: HttpClient) { }
getData(url: string): Observable<Record<string, any>> {
return this.http.get(url)
.pipe(map((res) => {
return res;
}))
}
}
The above example is based on this blog post, with the fix mentioned in my earlier post.
Example ideal usage for what I want:
<div>
<my-component data-source="./localPath/data1.json" />
<my-component data-source="./localPath/data2.json" />
</div>
Where data1.json
and data2.json
are two different files to be used as data sources respectively.