In these articles, we will retrieve static JSON data from the ionic project. We are not using the angular http service component to retrieve local a static JSON. Just for a simple example file to use fetch function of javascript to retrieve JSON data.
The Fetch API is a newer built-in feature of JavaScript that makes working with requests and responses easier.
The fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.
Example of Ionic json data
Step for getting static local data in the project.
Step 1: Create a project
ionic start blank localJson
cd localJson
Step 2: Create folder data in an asset in the project and add a new file called data.ts in the data folder and add the following data in a local JSON file.
[
{"name":"Ram", "company":"Google"},
{"name":"Bob", "company":"EMC"},
{"name":"Ram", "company":"Google"},
{"name":"Bob", "company":"EMC"},
{"name":"Ram", "company":"Google"},
{"name":"Bob", "company":"EMC"}
]
Step 3: Add the following code in a home.ts file and use the fetch API to retrieve local JSON data on the home page. The Fetch API provides an interface for fetching resources (including across the network).
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
data: any;
constructor() { }
ngOnInit() {
fetch('./assets/data/datajson.json').then(res => res.json())
.then(json => {
this.data = json;
});
}
}
Step 4: In-home template add the following code, we will use ngFor directive to loop in our array data.
<ion-header>
<ion-toolbar>
<ion-title>Local Json in Ionic 4</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-grid>
<ion-row *ngFor="let item of data; index as i">
<ion-col size="1">{{ i+ 1 }}</ion-col>
<ion-col size="3"> {{ item.name }}</ion-col>
<ion-col size="3"> {{ item.company }}</ion-col>
</ion-row>
</ion-grid>
</ion-content>
Related posts
- How to implement an ionic slider
- Complete guide on an ionic grid with an example
- How to implement an ionic alert controller.