Different Ways To Read Local JSON Files In Angular Application (2024)

Different Ways To Read Local JSON Files In Angular Application (1)

Table of Contents

1. Using the import statement

2. Using Angular HttpClient


In this tutorial, I am going to create a sample application to show how to use local JSON files in an Angular application. There are different ways to read local JSON files in Angular. we’ll see different ways to read local JSON files in Angular for example.

It turns out there are at least a couple of ways to do it. I will mention the most common ones:

  1. Using the import statement
  2. Using Angular HttpClient

Step 1: Create a new Angular Project

Create an angular project using the CLI command:

ng new json-read-example

Step 2: Create a new JSON file under the assets folder

We’ll create dummy JSON data files that will be containing a list of students.

[ { "id": 1, "name": "Luca", "email": "[email protected]", "gender": "male" }, { "id": 2, "name": "Lilly", "email": "[email protected]", "gender": "female" }, { "id": 3, "name": "Anna", "email": "[email protected]", "gender": "female" }, { "id": 4, "name": "John", "email": "[email protected]", "gender": "male" }, { "id": 5, "name": "Mary", "email": "[email protected]", "gender": "female" } ] 

Step 3: Methods for Reading Local JSON Files

1. Using the import statement

One way to read a JSON file from the assets folder in Angular is to use the import statement in your component.

import { Component, OnInit } from '@angular/core';import * as studentData from '../assets/students.json';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent implements OnInit { title = 'json-read-example'; data: any = studentData; ngOnInit() { console.log('Data', this.data); }}

You need to add "resolveJsonModule": true in the compilerOptions of your tsconfig.json the file that is at the root of your Angular application.

{ "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "resolveJsonModule": true }, "angularCompilerOptions": { }}

2. Using Angular HttpClient

A second way to read a JSON file from the assets folder in Angular is to use the HttpClient Now let’s see an example of it.

Import HttpClientModule in our root module. (app.module.ts) like below:

import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { HttpClientModule } from '@angular/common/http';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }

In this case, we simply subscribe to the Observable generated by Angular HttpClient and log the data in the console

The HTTP protocol is utilized by the majority of front-end apps to connect with the server. When working with an application that uses Angular, we may make use of the HttpClient service available from the @angular/common/http package to read JSON files from an Angular application.

import { Component, OnInit } from '@angular/core';import { HttpClient } from '@angular/common/http';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent implements OnInit { title = 'json-read-example'; studentData:any; url: string = '/assets/students.json'; constructor(private http: HttpClient) {} ngOnInit() { this.http.get(this.url).subscribe(res => { this.studentData = res; }); }}

Display table view using the below file

<p>Read Local JSON file student data using typescript HttpClient</p><table id="student"><tr><th>Name</th><th>Email</th></tr><tr *ngFor="let student of studentData"><td>{{student.name}}</td><td>{{student.email}}</td></tr></table>

Some other way to read JSON file

  1. use the fetch API
  2. use angular jsonPipe

Use the fetch API

We use Javascript fetch API to retrieve our static JSON file. Which is available in all browsers.

This is an example Angular 14 component that uses the Fetch API to read a JSON file:

import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent implements OnInit { title = 'json-read-example'; studentData:any; url: string = '/assets/students.json'; constructor() {} ngOnInit() { fetch(this.url).then(res => res.json()) .then(json => { this.studentData = json; }); }}

Use angular jsonPipe

This is good to know, even if it is not a way to read data from a JSON file.

Angular JSON pipe is mostly useful for debugging and this pipe creates a JSON representation of a data value.

The JSON pipe can be used as follows:

<p>{{ data | json}}</p>

Thank you everyone for reading the tutorial. I hope you enhanced your knowledge of Angular.

Projects Completed till now.

Discover how we can help your business grow.

"Third Rock Techkno's work integrates complex frameworks and features to offer everything researchers need. They are open-minded and worked smoothly with the academic subject matter."

- Dr Daniel T. Michaels, NINS

Different Ways To Read Local JSON Files In Angular Application (2024)
Top Articles
Zo krijg je betaald om boeken te lezen – Nijhof & Lee Blog
Minerusdt.io (Minerusdt Cryptocurrency Scam) Reviews
Safety Jackpot Login
Blorg Body Pillow
Genesis Parsippany
Trevor Goodwin Obituary St Cloud
Ffxiv Shelfeye Reaver
Combat level
Tyson Employee Paperless
Repentance (2 Corinthians 7:10) – West Palm Beach church of Christ
Driving Directions To Fedex
How to change your Android phone's default Google account
Comcast Xfinity Outage in Kipton, Ohio
Nordstrom Rack Glendale Photos
craigslist: south coast jobs, apartments, for sale, services, community, and events
Www Craigslist Louisville
Paula Deen Italian Cream Cake
The Haunted Drury Hotels of San Antonio’s Riverwalk
Lesson 3 Homework Practice Measures Of Variation Answer Key
Youtube Combe
Moe Gangat Age
Simon Montefiore artikelen kopen? Alle artikelen online
Hartland Liquidation Oconomowoc
Viha Email Login
Saatva Memory Foam Hybrid mattress review 2024
13301 South Orange Blossom Trail
Cal State Fullerton Titan Online
8002905511
Craigslist Gigs Norfolk
Phone number detective
Palmadise Rv Lot
2012 Street Glide Blue Book Value
Seymour Johnson AFB | MilitaryINSTALLATIONS
Orangetheory Northville Michigan
Naya Padkar Newspaper Today
The Blackening Showtimes Near Regal Edwards Santa Maria & Rpx
Los Garroberros Menu
Mckinley rugzak - Mode accessoires kopen? Ruime keuze
All Obituaries | Sneath Strilchuk Funeral Services | Funeral Home Roblin Dauphin Ste Rose McCreary MB
Chathuram Movie Download
Valls family wants to build a hotel near Versailles Restaurant
Citizens Bank Park - Clio
About Us
Top 1,000 Girl Names for Your Baby Girl in 2024 | Pampers
8 4 Study Guide And Intervention Trigonometry
Theater X Orange Heights Florida
Skyward Login Wylie Isd
Tommy Gold Lpsg
Marion City Wide Garage Sale 2023
Bomgas Cams
Tamilyogi Cc
Ff14 Palebloom Kudzu Cloth
Latest Posts
Article information

Author: Lilliana Bartoletti

Last Updated:

Views: 5621

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Lilliana Bartoletti

Birthday: 1999-11-18

Address: 58866 Tricia Spurs, North Melvinberg, HI 91346-3774

Phone: +50616620367928

Job: Real-Estate Liaison

Hobby: Graffiti, Astronomy, Handball, Magic, Origami, Fashion, Foreign language learning

Introduction: My name is Lilliana Bartoletti, I am a adventurous, pleasant, shiny, beautiful, handsome, zealous, tasty person who loves writing and wants to share my knowledge and understanding with you.