How to load local JSON File in Angular Application

JSON, i.e., JavaScript Object Notation is a lightweight format for interchanging data. It is based on a subset of JavaScript language. For example, this JSON data format is used in the webservice response. In old days webservices used XML for the primary data format but nowadays JSON, being lightweight, is becoming the preferred data format for exchanging data for most of the webservices.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, the JSON structure is realized as an object, record, struct, dictionary, hash table, keyed list, or an associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Here I am going to show you how to load local JSON file in your Angular project. Situation may arise when you want to do a quick POC (Proof of Concept) and you need some data for your POC to be tested right away and connecting to a database or an external persistence system requires you to write more code then local JSON file will help you provide data quickly.

Prerequisites

Angular 9/10, JSON File, How to create Angular project

The name of the project for this example is angular-load-local-json.

Sample JSON File

I am using here simple JSON file with some string values in an array. The content of the file is given below. You can download the whole source code later from the Source Code section at the end of this tutorial. The file name is results.json and kept under src/data folder.

[
	"Lorem Ipsum is simply dummy text of the printing and typesetting",
	"Lorem Ipsum has been the industry's standard dummy",
	"nd scrambled it to make a type specimen book. It",
	"typesetting, remaining essentially unchanged. It ",
	"sum passages, and more recently with desktop publi",
	"Contrary to popular belief, Lorem Ipsum is not sim",
	"professor at Hampden-Sydney College in Virginia, looked up one",
	"passage, and going through the cites of the word in",
	"comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum",
	"BC. This book is a treatise on the theory of ethics, very popu",
	"here are many variations of passages of Lorem Ipsum availa",
	"believable. If you are going to use a passage of Lorem Ips",
	"middle of text. All the Lorem Ipsum generators on the Intern",
	"tend to repeat predefined chunks as necessary, making this the",
	"first true generator on the Internet. It uses a dictionary of over 20",
	"he standard chunk of Lorem Ipsum used since the 1500s i",
	"1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are als",
	"reproduced in their exact original form, accompanied by English",
	"eadable content of a page when looking at its layout. The point"
]

Service Class

The service class basically loads the JSON from the directory location and returns the content to caller. make sure to put the content type as application/json in the response header.

To create a service typescript you need to execute the command ng g s file. Here I am creating file service. The below code is written into file.service.ts file under src/app folder.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class FileService {
  
	constructor(private http: HttpClient) { }

	getResultList() {
		const headers = new HttpHeaders({ 'Content-Type': 'application/json' })
        return this.http.get('./assets/data/results.json', { headers });
    }
}

Angular Module

In the Angular module you need to configure all modules you are going to use throughout your application. For example, I have added two additional modules – file service and http client. The below code is written into app.module.ts under src/app folder.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { HttpClientModule }    from '@angular/common/http';
import { FileService } from './file.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
	HttpClientModule
  ],
  providers: [FileService],
  bootstrap: [AppComponent]
})
export class AppModule { }

App Component

Next is the app component typescript file called src/app/app.component.ts file where you need to call the file service function to display on the UI (user Interface or front end).

import { Component, OnInit } from '@angular/core';

import { FileService } from './file.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

	results: any[] = [];
	
	constructor(private fileService: FileService) { }
	
	ngOnInit() {
		this.fileService.getResultList().subscribe(sr => {Object.assign(this.results, sr);});
	}
	
}

The UI file is an HTML file and the below code is written into app.component.html under src/app folder. Here I am retrieving the index value while iterating the values through loop.

<router-outlet></router-outlet>

<div *ngFor="let r of results; let i = index">
	<p>{{i+1}}. {{r}}</p>
</div>

Testing the Application

Once you are done with coding or implementation part you can execute command ng serve --open on your project’s root directory from command line tool and you will see the below output on your browser. The default browser automatically opens at http://localhost:4200 once the application compiles and deploys successfully.

angular load local json file

Hope you got idea how to load local JSON file into your Angular project.

Source Code

Download

Leave a Comment