Reading Local JSON files in angular 5
Posted By : Sushmit Gaur | 29-Jul-2018
In angular 5 there is not built in directive or module to import JSON files in any component easily. So, how do we read a local JSON file located in the angular project itself?
Well, the most popular approach to tackle this is to use AJAX. AJAX helps to fetch a JSON file through HTTP calls while the page is loading which automatically resolves two issues.
One is that since the JSON file is not really part of your code it reduces the file size of your code and hence improves performance. Second is that since ajax is asynchronous and fetches data over HTTP call doesn't require the whole page to refresh when the data is fetched which also improves performance and user experience.
Following is the most common and popular code to fetch JSON using angular built-in modules for making HTTP calls:
In above code, we have taken advantage of angular 2's HTTP Class ‘@angular/http’.
Now the Downside of above approach is that if a user enables offline mode in his/her browser or the internet connection is lost our Ajax will not work and eventually our JSON will not load as well.
Now there's another approach to fix the above issue and that is to convert complete JSON to a variable in a typescript file and export them, and where ever required import and then use it as shown in the code below:
The above method works but this approach increases the app size and will require more memory at runtime.
There is also another method which uses node.js's require method which looks something like this:
The above method works as well but there is an even better way to do the same with less hassle.
First, create a new file with name "json-typings.d.ts" right next to index.html in an angular project. add following code to it:
Now use following code to import any JSON file in your project in any desired component:
The last approach appears to be a clearer solution to the problem.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Sushmit Gaur
Sushmit is a self taught programmer, having experience in UI Development for Web Applications. With Experience of 3 months as an intern in React.js technology looking forward to learn new skill set and challenges for further assessment in career.