Reading Local JSON Data With The Fetch API
While tinkering with a small Angular project, I needed to pull data from a JSON file stored in src/assets.
Angular offers multiple approaches to load JSON files, but the one below is the most straightforward if you're just getting started with the framework.
Leverage The Native Fetch API
That's really all there is to it! No imports are required, neither HttpClient nor RxJS knowledge is needed.
The Fetch API ships with every modern browser and works perfectly for reading local JSON files.
The following code fetches the content of the JSON file and outputs it to the browser console:
// app.component.ts
ngOnInit(): void {
fetch('./assets/data.json').then(res => res.json())
.then(console.log); // do something with data
}
Important Considerations
Is this the ideal solution? Absolutely not!
At least two superior approaches exist for loading JSON files from a local directory:
- Using the ES6
importstatement - Using Angular's
HttpClient
Furthermore, fetching data inside a dedicated service is a better architectural pattern, yet I placed the call in ngOnInit to keep the example concise.
Still, for newcomers to Angular, this remains the simplest path forward.
If you haven't yet worked with HttpClient and RxJS, consider this a temporary workaround. Don't settle here!
Eventually, you'll want to master HttpClient and RxJS to build production-ready apps.
What are your thoughts? I'm eager to hear other perspectives on this!
