Reading a Local Text File in Angular2
There are unlike ways to read local Json file in Angular. In this example, nosotros'll see iii different means to read local JSON file in Angular with example. We'll too meet how to read and display the data from JSON file in angular.
Different ways to read local JSON file.
- Reading JSON file using typescript import statement.
- Reading JSON file using Angular HttpClient.
- Reading JSON file using ES6+ import statement for offline Athwart apps.
Generate project
Create new angular project using the following angular cli control.
ng new angular-read-local-json-file
and then you'll be asked to choose the stylesheet format, select your preferred format and hit enter.

Then Angular CLI will create necessary file and folders and will install the necessary npm packages.
Navigate to project directory
cd angular-read-local-json-file
Create Dummy Json Data File
We'll create dummy json data files which will exist containing listing of employees.
src/avails/employees.json
{ "employees": [ { "id": "1", "firstName": "Tom", "lastName": "Prowl" }, { "id": "2", "firstName": "Maria", "lastName": "Sharapova" }, { "id": "3", "firstName": "James", "lastName": "Bond" } ] }
Method 1. Import JSON file using typescript import statement
Athwart 6.1 released with the support of typescript ii.nine. and Typescript 2.ix released with resolveJsonModule
--resolveJsonModule
allows for importing, extracting types from and generating .json
files.
Now nosotros'll create a new component which volition read json file using import statement.
create new component using the following command:
ng generate component read-json-using-typescript-import
so our component will looks equally following:
read-json-using-typescript-import.ts
import { Component, OnInit } from "@angular/core"; import employees from "../../assets/employees.json"; @Component({ selector: "app-read-json-using-typescript-import", templateUrl: "./read-json-using-typescript-import.component.html", styleUrls: ["./read-json-using-typescript-import.component.css"] }) export class ReadJsonUsingTypescriptImportComponent implements OnInit { employeeData: whatever; constructor() { this.employeeData = employees; } ngOnInit() {} }
In the above lawmaking, we've imported JSON data using highlighted the 2d line and nosotros've assigned that information to employeeList
so that we can access it from the template file.
If you'll run the to a higher place code it'll throw the following error.
Error in src/app/read-json-using-typescript-import/read-json-using-typescript-import.component.ts (2:26) Cannot find module '../employees.json'. Consider using '--resolveJsonModule' to import module with '.json' extension
This mistake is indicating that employ--resolveJsonModule
compiler option that lets us import JSON modules from within TypeScript modules.
Now to add --resolveJsonModule
compiler pick, we'll demand to add following options tsconfig.json
as following
tsconfig.json
{ ... "compilerOptions": { ... "resolveJsonModule": true, "esModuleInterop": truthful .... } ... }
Now update the following alter in template file
read-json-using-typescript-import.component.html
<h2>Read Local JSON file data using typescript import</h2> <table id="employees"> <tr> <th>ID</thursday> <th>Start Proper name</th> <thursday>Last Name</th> </tr> <tr *ngFor="let employee of employeeData.employees"> <td>{{employee.id}}</td> <td>{{employee.firstName}}</td> <td>{{employee.lastName}}</td> </tr> </tabular array>
Update css file as following
#employees { font-family unit: "Trebuchet MS", Arial, Helvetica, sans-serif; edge-collapse: plummet; width: 100%; } #employees td, #employees th { border: 1px solid #ddd; padding: 8px; } #employees tr:nth-child(even){background-colour: #f2f2f2;} #employees tr:hover {groundwork-color: #ddd;} #employees th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-colour: scarlet; color: #fff; }
Output

Method 2: Import JSON file using Angular HttpClient.
This method will utilize athwart HttpClient to read local json file. Now let's see an example of information technology.
Now generate new component using the following control:
ng generate component read-json-file-using-httpclient
Now nosotros'll run into how can we use Athwart HttpClient to read local json file in angular.
We'll first need to import HttpClientModule in app.module.ts as following
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { ReadJsonUsingTypescriptImportComponent } from './read-json-using-typescript-import/read-json-using-typescript-import.component'; import { ReadJsonFileUsingHttpclientComponent } from './read-json-file-using-httpclient/read-json-file-using-httpclient.component'; @NgModule({ imports: [ BrowserModule, FormsModule ,HttpClientModule], declarations: [ AppComponent, ReadJsonUsingTypescriptImportComponent, ReadJsonFileUsingHttpclientComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
Update the component with the post-obit changes:
read-json-file-using-httpclient.component.ts
import { Component, OnInit } from '@angular/core'; import { HttpClient,HttpErrorResponse } from "@athwart/common/http"; import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators'; @Component({ selector: 'app-read-json-file-using-httpclient', templateUrl: './read-json-file-using-httpclient.component.html', styleUrls: ['./read-json-file-using-httpclient.component.css'] }) consign class ReadJsonFileUsingHttpclientComponent implements OnInit { employeeData:any; constructor(private httpClient: HttpClient){ } ngOnInit(){ this.httpClient.go<any>("assets/employees.json").subscribe((data)=> this.employeeData = data ) } }
Update template file with the following changes
read-json-file-using-httpclient.component.html
<h2>Read Local JSON file data using HttpClient</h2> <table id="employees"> <tr> <thursday>ID</th> <th>First Proper noun</thursday> <th>Terminal Name</th> </tr> <tr *ngFor="let employee of employeeData?.employees"> <td>{{employee.id}}</td> <td>{{employee.firstName}}</td> <td>{{employee.lastName}}</td> </tr> </table>
and update your css file with this changes.
#employees { font-family unit: "Trebuchet MS", Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; } #employees td, #employees th { border: 1px solid #ddd; padding: 8px; } #employees tr:nth-child(even){background-color: #f2f2f2;} #employees tr:hover {background-color: #ddd;} #employees th { padding-tiptop: 12px; padding-lesser: 12px; text-align: left; groundwork-colour: red; color: #fff; }
If you'll run this code, yous'll become the following output.
Output

Method 3: Reading JSON file using ES6+ import statement for offline Angular apps
Angular HttpClient volition not work when application goes offline. For offline angular app we have other fashion to read local json file in angular which is ES6+ import argument
Now we'll come across an case how tin can nosotros utilise ES6+ import to read local json file for offline app.
Add typing file src/app/json-typings.d.ts
declare module "*.json" { const value: any; export default value; }
and import json file same as first method.
read-json-file-using-es6.component.ts
import { Component, OnInit } from '@angular/core'; import employees from "../../assets/employees.json"; @Component({ selector: 'app-read-json-file-using-es6', templateUrl: './read-json-file-using-es6.component.html', styleUrls: ['./read-json-file-using-es6.component.css'] }) export course ReadJsonFileUsingEs6Component implements OnInit { employeeData: any; constructor() { this.employeeData = employees; } ngOnInit() { } }
Now update template file every bit following:
read-json-file-using-es6.component.html
<h2>Read Local JSON file data using ES6+</h2> <table id="employees"> <tr> <th>ID</th> <th>Start Name</th> <th>Last Name</thursday> </tr> <tr *ngFor="let employee of employeeData.employees"> <td>{{employee.id}}</td> <td>{{employee.firstName}}</td> <td>{{employee.lastName}}</td> </tr> </table>
read-json-file-using-es6.component.css
#employees { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; border-plummet: collapse; width: 100%; } #employees td, #employees th { edge: 1px solid #ddd; padding: 8px; } #employees tr:nth-child(fifty-fifty){background-color: #f2f2f2;} #employees tr:hover {background-color: #ddd;} #employees thursday { padding-top: 12px; padding-bottom: 12px; text-marshal: left; background-colour: red; color: #fff; }
Output

That's it for reading local json file in athwart. I hope you like this article.
Also Read
- Athwart Textile Select Modify Effect Example
- Athwart Fabric Date Range Picker
- What's new in Athwart x
- How to install angular material in Athwart Application
- How to use Angular APP_INITIALIZER token
- Integrate CKEditor(rich text editor) in Angular
- How to check Angular CLI version and how to update information technology.
- Different means to install bootstrap 4 in angular awarding
Source: https://www.elite-corner.com/2020/07/different-ways-to-read-local-json-file-in-angular-with-example.html
Post a Comment for "Reading a Local Text File in Angular2"