I was playing around with a small Angular app and I wanted to get some data from a json file that I saved in src/assets.
There are several ways to read a json file in an Angular app.
However, here is the easiest one for people approaching Angular from scratch.
Use The Fetch API
Simple like that!
You don't need to import anything, you don't need to use HttpClient and you don't need to know RxJS!
The native Fetch API is available in all browsers and it can be used to read local json files.
Here is the snippet of code that read the data in the json file and logs it in the console:
// app.component.ts
ngOnInit(): void {
fetch('./assets/data.json').then(res => res.json())
.then(console.log); // do something with data
}
Things To Remember
Is this the best way? No, it is not!
There are at least two better ways to read json data from a local folder:
- Use the import statement
- Use Angular HttpClient
On top of this, it would be better to fetch data in a service but for the sake of simplicity I did it in ngOnInit.
However, this is the easiest way for someone approaching Angular.
If you don't know Angular HttpClient and some RxJS, this is a patch. However, don't stop here!
Soon or later you will have to learn about Angular HttpClient and RxJS.
What is your take? I'd be curious to hear other opinions!
Top comments (0)