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": "luca@gmail.com", "gender": "male" }, { "id": 2, "name": "Lilly", "email": "lilly@gmail.com", "gender": "female" }, { "id": 3, "name": "Anna", "email": "anna@gmail.com", "gender": "female" }, { "id": 4, "name": "John", "email": "john@gmail.com", "gender": "male" }, { "id": 5, "name": "Mary", "email": "mary@gmail.com", "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
Can you retire on $2 million?
How to Write a Memo in 8 Steps
Is Paige Vanzant Related To Ronnie Van Zant
DPhil Research - List of thesis titles
Mountain Dew Bennington Pontoon
Immobiliare di Felice| Appartamento | Appartamento in vendita Porto San
Miss Carramello
Bellinghamcraigslist
Owatc Canvas
Lowes 385
Unraveling The Mystery: Does Breckie Hill Have A Boyfriend?
2013 Chevy Cruze Coolant Hose Diagram
Tiger Island Hunting Club
Hair Love Salon Bradley Beach
Learn2Serve Tabc Answers
Scenes from Paradise: Where to Visit Filming Locations Around the World - Paradise
Samantha Lyne Wikipedia
Swgoh Blind Characters
Never Give Up Quotes to Keep You Going
Chaos Space Marines Codex 9Th Edition Pdf
Military life insurance and survivor benefits | USAGov
Puretalkusa.com/Amac
Yisd Home Access Center
What Time Does Walmart Auto Center Open
Hampton University Ministers Conference Registration
Craigslistodessa
25 Best Things to Do in Palermo, Sicily (Italy)
Utexas Iot Wifi
Boise Craigslist Cars And Trucks - By Owner
Snohomish Hairmasters
The Collective - Upscale Downtown Milwaukee Hair Salon
Spirited Showtimes Near Marcus Twin Creek Cinema
Desales Field Hockey Schedule
The Rise of "t33n leaks": Understanding the Impact and Implications - The Digital Weekly
Flixtor Nu Not Working
Matlab Kruskal Wallis
Marine Forecast Sandy Hook To Manasquan Inlet
Barrage Enhancement Lost Ark
Wednesday Morning Gifs
The Land Book 9 Release Date 2023
Raising Canes Franchise Cost
ENDOCRINOLOGY-PSR in Lewes, DE for Beebe Healthcare
Sound Of Freedom Showtimes Near Lewisburg Cinema 8
Dragon Ball Super Super Hero 123Movies
Foxxequeen
Toomics - Die unendliche Welt der Comics online
Embry Riddle Prescott Academic Calendar
Tlc Africa Deaths 2021
Craigslist Pet Phoenix
City Of Irving Tx Jail In-Custody List
Buildapc Deals
Psalm 46 New International Version
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated:

Views: 5693

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.